diff --git a/.noir-sync-commit b/.noir-sync-commit index 23a34206cf8..f0dcc120514 100644 --- a/.noir-sync-commit +++ b/.noir-sync-commit @@ -1 +1 @@ -0864e7c945089cc06f8cc9e5c7d933c465d8c892 +5598059576c6cbc72474aff4b18bc5e4bb9f08e1 diff --git a/barretenberg/acir_tests/run_acir_tests.sh b/barretenberg/acir_tests/run_acir_tests.sh index 0a6cdbbb3fd..011dbfa5d64 100755 --- a/barretenberg/acir_tests/run_acir_tests.sh +++ b/barretenberg/acir_tests/run_acir_tests.sh @@ -41,7 +41,8 @@ SKIP_ARRAY=(diamond_deps_0 workspace workspace_default_member) # if HONK is false, we should skip verify_honk_proof if [ "$HONK" = false ]; then # Insert the new item into the array - SKIP_ARRAY+=(verify_honk_proof) + # TODO https://github.com/AztecProtocol/barretenberg/issues/1108 + SKIP_ARRAY+=(verify_honk_proof regression_5045) fi function test() { diff --git a/noir/noir-repo/acvm-repo/acir/src/circuit/black_box_functions.rs b/noir/noir-repo/acvm-repo/acir/src/circuit/black_box_functions.rs index fb7d9eb584c..6639f1fbe71 100644 --- a/noir/noir-repo/acvm-repo/acir/src/circuit/black_box_functions.rs +++ b/noir/noir-repo/acvm-repo/acir/src/circuit/black_box_functions.rs @@ -164,7 +164,15 @@ pub enum BlackBoxFunc { /// ultimately fail. RecursiveAggregation, - /// Addition over the embedded curve on which the witness is defined. + /// Addition over the embedded curve on which the witness is defined + /// The opcode makes the following assumptions but does not enforce them because + /// it is more efficient to do it only when required. For instance, adding two + /// points that are on the curve it guarantee to give a point on the curve. + /// + /// It assumes that the points are on the curve. + /// If the inputs are the same witnesses index, it will perform a doubling, + /// If not, it assumes that the points' x-coordinates are not equal. + /// It also assumes neither point is the infinity point. EmbeddedCurveAdd, /// BigInt addition diff --git a/noir/noir-repo/aztec_macros/src/transforms/functions.rs b/noir/noir-repo/aztec_macros/src/transforms/functions.rs index 39c0ca344e6..6c8af308a52 100644 --- a/noir/noir-repo/aztec_macros/src/transforms/functions.rs +++ b/noir/noir-repo/aztec_macros/src/transforms/functions.rs @@ -316,14 +316,17 @@ fn create_static_check(fname: &str, is_private: bool) -> Statement { .iter() .fold(variable("context"), |acc, member| member_access(acc, member)) }; - make_statement(StatementKind::Constrain(ConstrainStatement( - make_eq(is_static_call_expr, expression(ExpressionKind::Literal(Literal::Bool(true)))), - Some(expression(ExpressionKind::Literal(Literal::Str(format!( - "Function {} can only be called statically", - fname - ))))), - ConstrainKind::Assert, - ))) + make_statement(StatementKind::Constrain(ConstrainStatement { + kind: ConstrainKind::Assert, + arguments: vec![ + make_eq(is_static_call_expr, expression(ExpressionKind::Literal(Literal::Bool(true)))), + expression(ExpressionKind::Literal(Literal::Str(format!( + "Function {} can only be called statically", + fname + )))), + ], + span: Default::default(), + })) } /// Creates a check for internal functions ensuring that the caller is self. @@ -332,17 +335,20 @@ fn create_static_check(fname: &str, is_private: bool) -> Statement { /// assert(context.msg_sender() == context.this_address(), "Function can only be called internally"); /// ``` fn create_internal_check(fname: &str) -> Statement { - make_statement(StatementKind::Constrain(ConstrainStatement( - make_eq( - method_call(variable("context"), "msg_sender", vec![]), - method_call(variable("context"), "this_address", vec![]), - ), - Some(expression(ExpressionKind::Literal(Literal::Str(format!( - "Function {} can only be called internally", - fname - ))))), - ConstrainKind::Assert, - ))) + make_statement(StatementKind::Constrain(ConstrainStatement { + kind: ConstrainKind::Assert, + arguments: vec![ + make_eq( + method_call(variable("context"), "msg_sender", vec![]), + method_call(variable("context"), "this_address", vec![]), + ), + expression(ExpressionKind::Literal(Literal::Str(format!( + "Function {} can only be called internally", + fname + )))), + ], + span: Default::default(), + })) } /// Creates a call to assert_initialization_matches_address_preimage to be inserted diff --git a/noir/noir-repo/aztec_macros/src/utils/parse_utils.rs b/noir/noir-repo/aztec_macros/src/utils/parse_utils.rs index efa31860b6e..61f54377284 100644 --- a/noir/noir-repo/aztec_macros/src/utils/parse_utils.rs +++ b/noir/noir-repo/aztec_macros/src/utils/parse_utils.rs @@ -243,10 +243,7 @@ fn empty_statement(statement: &mut Statement) { } fn empty_constrain_statement(constrain_statement: &mut ConstrainStatement) { - empty_expression(&mut constrain_statement.0); - if let Some(expression) = &mut constrain_statement.1 { - empty_expression(expression); - } + empty_expressions(&mut constrain_statement.arguments); } fn empty_expressions(expressions: &mut [Expression]) { diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs b/noir/noir-repo/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs index c4f0e944099..8929122f515 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs @@ -666,7 +666,7 @@ impl<'block> BrilligBlock<'block> { self.brillig_context.deallocate_register(items_pointer); } - Instruction::ArraySet { array, index, value, mutable: _ } => { + Instruction::ArraySet { array, index, value, mutable } => { let source_variable = self.convert_ssa_value(*array, dfg); let index_register = self.convert_ssa_single_addr_value(*index, dfg); let value_variable = self.convert_ssa_value(*value, dfg); @@ -688,6 +688,7 @@ impl<'block> BrilligBlock<'block> { destination_variable, index_register, value_variable, + *mutable, ); } Instruction::RangeCheck { value, max_bit_size, assert_message } => { @@ -868,6 +869,7 @@ impl<'block> BrilligBlock<'block> { destination_variable: BrilligVariable, index_register: SingleAddrVariable, value_variable: BrilligVariable, + mutable: bool, ) { assert!(index_register.bit_size == BRILLIG_MEMORY_ADDRESSING_BIT_SIZE); match (source_variable, destination_variable) { @@ -875,20 +877,26 @@ impl<'block> BrilligBlock<'block> { BrilligVariable::BrilligArray(source_array), BrilligVariable::BrilligArray(destination_array), ) => { - self.brillig_context.call_array_copy_procedure(source_array, destination_array); + if !mutable { + self.brillig_context.call_array_copy_procedure(source_array, destination_array); + } } ( BrilligVariable::BrilligVector(source_vector), BrilligVariable::BrilligVector(destination_vector), ) => { - self.brillig_context.call_vector_copy_procedure(source_vector, destination_vector); + if !mutable { + self.brillig_context + .call_vector_copy_procedure(source_vector, destination_vector); + } } _ => unreachable!("ICE: array set on non-array"), } + let destination_for_store = if mutable { source_variable } else { destination_variable }; // Then set the value in the newly created array let items_pointer = - self.brillig_context.codegen_make_array_or_vector_items_pointer(destination_variable); + self.brillig_context.codegen_make_array_or_vector_items_pointer(destination_for_store); self.brillig_context.codegen_store_with_offset( items_pointer, @@ -896,6 +904,14 @@ impl<'block> BrilligBlock<'block> { value_variable.extract_register(), ); + // If we mutated the source array we want instructions that use the destination array to point to the source array + if mutable { + self.brillig_context.mov_instruction( + destination_variable.extract_register(), + source_variable.extract_register(), + ); + } + self.brillig_context.deallocate_register(items_pointer); } diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs index 3d428e97622..b0f283eeaeb 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs @@ -1471,6 +1471,7 @@ impl AcirContext { | BlackBoxFunc::AND | BlackBoxFunc::XOR | BlackBoxFunc::AES128Encrypt + | BlackBoxFunc::EmbeddedCurveAdd ); // Convert `AcirVar` to `FunctionInput` let inputs = self.prepare_inputs_for_black_box_func_call(inputs, allow_constant_inputs)?; diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs index 430801dacf6..15d72c2ae74 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs @@ -450,7 +450,12 @@ impl<'a> Context<'a> { warnings.extend(self.acir_context.warnings.clone()); // Add the warnings from the alter Ssa passes - Ok(self.acir_context.finish(input_witness, return_witnesses, warnings)) + Ok(self.acir_context.finish( + input_witness, + // Don't embed databus return witnesses into the circuit. + if self.data_bus.return_data.is_some() { Vec::new() } else { return_witnesses }, + warnings, + )) } fn initialize_databus( diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/ir/function.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/ir/function.rs index 65a616ef612..1466f2e5d44 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/ir/function.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/ir/function.rs @@ -160,6 +160,17 @@ impl Function { let returns = vecmap(self.returns(), |ret| self.dfg.type_of_value(*ret)); Signature { params, returns } } + + /// Finds the block of the function with the Return instruction + pub(crate) fn find_last_block(&self) -> BasicBlockId { + for block in self.reachable_blocks() { + if matches!(self.dfg[block].terminator(), Some(TerminatorInstruction::Return { .. })) { + return block; + } + } + + unreachable!("SSA Function {} has no reachable return instruction!", self.id()) + } } impl std::fmt::Display for RuntimeType { diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/array_set.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/array_set.rs index cf61d7fd73f..491a17adb66 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/array_set.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/array_set.rs @@ -16,14 +16,17 @@ impl Ssa { #[tracing::instrument(level = "trace", skip(self))] pub(crate) fn array_set_optimization(mut self) -> Self { for func in self.functions.values_mut() { - if !func.runtime().is_entry_point() { - let mut reachable_blocks = func.reachable_blocks(); + let mut reachable_blocks = func.reachable_blocks(); + let block = if !func.runtime().is_entry_point() { assert_eq!(reachable_blocks.len(), 1, "Expected there to be 1 block remaining in Acir function for array_set optimization"); + reachable_blocks.pop_first().unwrap() + } else { + // We only apply the array set optimization in the return block of Brillig functions + func.find_last_block() + }; - let block = reachable_blocks.pop_first().unwrap(); - let instructions_to_update = analyze_last_uses(&func.dfg, block); - make_mutable(&mut func.dfg, block, instructions_to_update); - } + let instructions_to_update = analyze_last_uses(&func.dfg, block); + make_mutable(&mut func.dfg, block, instructions_to_update); } self } diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/mem2reg.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/mem2reg.rs index ba65cef21b5..68c04e3b4b4 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/mem2reg.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/mem2reg.rs @@ -288,6 +288,8 @@ impl<'f> PerFunctionContext<'f> { .filter(|param| self.inserter.function.dfg.value_is_reference(**param)) .collect::>(); + // Must collect here as we are immutably borrowing `self` to fetch the reference parameters + let mut values_to_reduce_counts = Vec::new(); for (allocation, instruction) in &references.last_stores { if let Some(expression) = references.expressions.get(allocation) { if let Some(aliases) = references.aliases.get(expression) { @@ -297,13 +299,15 @@ impl<'f> PerFunctionContext<'f> { // If `allocation_aliases_parameter` is known to be false if allocation_aliases_parameter == Some(false) { self.instructions_to_remove.insert(*instruction); - if let Some(context) = self.load_results.get_mut(allocation) { - context.uses -= 1; - } + values_to_reduce_counts.push(*allocation); } } } } + + for value in values_to_reduce_counts { + self.reduce_load_result_count(value); + } } fn increase_load_ref_counts(&mut self, value: ValueId) { @@ -406,12 +410,8 @@ impl<'f> PerFunctionContext<'f> { else { panic!("Should have a store instruction here"); }; - if let Some(context) = self.load_results.get_mut(&address) { - context.uses -= 1; - } - if let Some(context) = self.load_results.get_mut(&value) { - context.uses -= 1; - } + self.reduce_load_result_count(address); + self.reduce_load_result_count(value); } let known_value = references.get_known_value(value); @@ -419,12 +419,8 @@ impl<'f> PerFunctionContext<'f> { let known_value_is_address = known_value == address; if known_value_is_address { self.instructions_to_remove.insert(instruction); - if let Some(context) = self.load_results.get_mut(&address) { - context.uses -= 1; - } - if let Some(context) = self.load_results.get_mut(&value) { - context.uses -= 1; - } + self.reduce_load_result_count(address); + self.reduce_load_result_count(value); } else { references.last_stores.insert(address, instruction); } @@ -617,6 +613,13 @@ impl<'f> PerFunctionContext<'f> { } } + fn reduce_load_result_count(&mut self, value: ValueId) { + if let Some(context) = self.load_results.get_mut(&value) { + // TODO this was saturating https://github.com/noir-lang/noir/issues/6124 + context.uses = context.uses.wrapping_sub(1); + } + } + fn recursively_add_values(&self, value: ValueId, set: &mut HashSet) { set.insert(value); if let Some((elements, _)) = self.inserter.function.dfg.get_array_constant(value) { @@ -741,7 +744,8 @@ impl<'f> PerFunctionContext<'f> { if all_loads_removed && !store_alias_used { self.instructions_to_remove.insert(*store_instruction); if let Some((_, counter)) = remaining_last_stores.get_mut(store_address) { - *counter -= 1; + // TODO this was saturating https://github.com/noir-lang/noir/issues/6124 + *counter = counter.wrapping_sub(1); } } else if let Some((_, counter)) = remaining_last_stores.get_mut(store_address) { *counter += 1; diff --git a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/rc.rs b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/rc.rs index 4f109a27874..1750f2d80a5 100644 --- a/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/rc.rs +++ b/noir/noir-repo/compiler/noirc_evaluator/src/ssa/opt/rc.rs @@ -2,9 +2,8 @@ use std::collections::{HashMap, HashSet}; use crate::ssa::{ ir::{ - basic_block::BasicBlockId, function::Function, - instruction::{Instruction, InstructionId, TerminatorInstruction}, + instruction::{Instruction, InstructionId}, types::Type, value::ValueId, }, @@ -107,7 +106,7 @@ impl Context { /// Find each dec_rc instruction and if the most recent inc_rc instruction for the same value /// is not possibly mutated, then we can remove them both. Returns each such pair. fn find_rcs_to_remove(&mut self, function: &Function) -> HashSet { - let last_block = Self::find_last_block(function); + let last_block = function.find_last_block(); let mut to_remove = HashSet::new(); for instruction in function.dfg[last_block].instructions() { @@ -124,20 +123,6 @@ impl Context { to_remove } - /// Finds the block of the function with the Return instruction - fn find_last_block(function: &Function) -> BasicBlockId { - for block in function.reachable_blocks() { - if matches!( - function.dfg[block].terminator(), - Some(TerminatorInstruction::Return { .. }) - ) { - return block; - } - } - - unreachable!("SSA Function {} has no reachable return instruction!", function.id()) - } - /// Finds and pops the IncRc for the given array value if possible. fn pop_rc_for(&mut self, value: ValueId, function: &Function) -> Option { let typ = function.dfg.type_of_value(value); diff --git a/noir/noir-repo/compiler/noirc_frontend/src/ast/statement.rs b/noir/noir-repo/compiler/noirc_frontend/src/ast/statement.rs index d67501e932b..49568d42038 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/ast/statement.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/ast/statement.rs @@ -562,7 +562,27 @@ pub enum LValue { } #[derive(Debug, PartialEq, Eq, Clone)] -pub struct ConstrainStatement(pub Expression, pub Option, pub ConstrainKind); +pub struct ConstrainStatement { + pub kind: ConstrainKind, + pub arguments: Vec, + pub span: Span, +} + +impl Display for ConstrainStatement { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.kind { + ConstrainKind::Assert | ConstrainKind::AssertEq => write!( + f, + "{}({})", + self.kind, + vecmap(&self.arguments, |arg| arg.to_string()).join(", ") + ), + ConstrainKind::Constrain => { + write!(f, "constrain {}", &self.arguments[0]) + } + } + } +} #[derive(Debug, PartialEq, Eq, Clone, Copy)] pub enum ConstrainKind { @@ -571,6 +591,25 @@ pub enum ConstrainKind { Constrain, } +impl ConstrainKind { + pub fn required_arguments_count(&self) -> usize { + match self { + ConstrainKind::Assert | ConstrainKind::Constrain => 1, + ConstrainKind::AssertEq => 2, + } + } +} + +impl Display for ConstrainKind { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + ConstrainKind::Assert => write!(f, "assert"), + ConstrainKind::AssertEq => write!(f, "assert_eq"), + ConstrainKind::Constrain => write!(f, "constrain"), + } + } +} + #[derive(Debug, PartialEq, Eq, Clone)] pub enum Pattern { Identifier(Ident), @@ -885,12 +924,6 @@ impl Display for LetStatement { } } -impl Display for ConstrainStatement { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!(f, "constrain {}", self.0) - } -} - impl Display for AssignStatement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{} = {}", self.lvalue, self.expression) diff --git a/noir/noir-repo/compiler/noirc_frontend/src/ast/visitor.rs b/noir/noir-repo/compiler/noirc_frontend/src/ast/visitor.rs index 9a2fb79ca88..fb116d34e8a 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/ast/visitor.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/ast/visitor.rs @@ -1117,11 +1117,7 @@ impl ConstrainStatement { } pub fn accept_children(&self, visitor: &mut impl Visitor) { - self.0.accept(visitor); - - if let Some(exp) = &self.1 { - exp.accept(visitor); - } + visit_expressions(&self.arguments, visitor); } } diff --git a/noir/noir-repo/compiler/noirc_frontend/src/elaborator/statements.rs b/noir/noir-repo/compiler/noirc_frontend/src/elaborator/statements.rs index 543cf20b647..2d46c4c6341 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/elaborator/statements.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/elaborator/statements.rs @@ -1,7 +1,10 @@ -use noirc_errors::{Location, Span}; +use noirc_errors::{Location, Span, Spanned}; use crate::{ - ast::{AssignStatement, ConstrainStatement, LValue}, + ast::{ + AssignStatement, BinaryOpKind, ConstrainKind, ConstrainStatement, Expression, + ExpressionKind, InfixExpression, LValue, + }, hir::{ resolution::errors::ResolverError, type_check::{Source, TypeCheckError}, @@ -110,12 +113,51 @@ impl<'context> Elaborator<'context> { (HirStatement::Let(let_), Type::Unit) } - pub(super) fn elaborate_constrain(&mut self, stmt: ConstrainStatement) -> (HirStatement, Type) { - let expr_span = stmt.0.span; - let (expr_id, expr_type) = self.elaborate_expression(stmt.0); + pub(super) fn elaborate_constrain( + &mut self, + mut stmt: ConstrainStatement, + ) -> (HirStatement, Type) { + let span = stmt.span; + let min_args_count = stmt.kind.required_arguments_count(); + let max_args_count = min_args_count + 1; + let actual_args_count = stmt.arguments.len(); + + let (message, expr) = if !(min_args_count..=max_args_count).contains(&actual_args_count) { + self.push_err(TypeCheckError::AssertionParameterCountMismatch { + kind: stmt.kind, + found: actual_args_count, + span, + }); + + // Given that we already produced an error, let's make this an `assert(true)` so + // we don't get further errors. + let message = None; + let kind = ExpressionKind::Literal(crate::ast::Literal::Bool(true)); + let expr = Expression { kind, span }; + (message, expr) + } else { + let message = + (actual_args_count != min_args_count).then(|| stmt.arguments.pop().unwrap()); + let expr = match stmt.kind { + ConstrainKind::Assert | ConstrainKind::Constrain => stmt.arguments.pop().unwrap(), + ConstrainKind::AssertEq => { + let rhs = stmt.arguments.pop().unwrap(); + let lhs = stmt.arguments.pop().unwrap(); + let span = Span::from(lhs.span.start()..rhs.span.end()); + let operator = Spanned::from(span, BinaryOpKind::Equal); + let kind = + ExpressionKind::Infix(Box::new(InfixExpression { lhs, operator, rhs })); + Expression { kind, span } + } + }; + (message, expr) + }; + + let expr_span = expr.span; + let (expr_id, expr_type) = self.elaborate_expression(expr); // Must type check the assertion message expression so that we instantiate bindings - let msg = stmt.1.map(|assert_msg_expr| self.elaborate_expression(assert_msg_expr).0); + let msg = message.map(|assert_msg_expr| self.elaborate_expression(assert_msg_expr).0); self.unify(&expr_type, &Type::Bool, || TypeCheckError::TypeMismatch { expr_typ: expr_type.to_string(), diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/display.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/display.rs new file mode 100644 index 00000000000..143e0450bac --- /dev/null +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/display.rs @@ -0,0 +1,865 @@ +use std::{fmt::Display, rc::Rc}; + +use iter_extended::vecmap; +use noirc_errors::Span; + +use crate::{ + ast::{ + ArrayLiteral, AsTraitPath, AssignStatement, BlockExpression, CallExpression, + CastExpression, ConstrainStatement, ConstructorExpression, Expression, ExpressionKind, + ForLoopStatement, ForRange, GenericTypeArgs, IfExpression, IndexExpression, + InfixExpression, LValue, Lambda, LetStatement, Literal, MemberAccessExpression, + MethodCallExpression, Pattern, PrefixExpression, Statement, StatementKind, UnresolvedType, + UnresolvedTypeData, + }, + hir_def::traits::TraitConstraint, + macros_api::NodeInterner, + node_interner::InternedStatementKind, + token::{Keyword, Token}, + Type, +}; + +use super::{ + value::{ExprValue, TypedExpr}, + Value, +}; + +pub(super) fn display_quoted( + tokens: &[Token], + indent: usize, + interner: &NodeInterner, + f: &mut std::fmt::Formatter<'_>, +) -> std::fmt::Result { + if tokens.is_empty() { + write!(f, "quote {{ }}") + } else { + writeln!(f, "quote {{")?; + let indent = indent + 1; + write!(f, "{}", " ".repeat(indent * 4))?; + display_tokens(tokens, interner, indent, f)?; + writeln!(f)?; + let indent = indent - 1; + write!(f, "{}", " ".repeat(indent * 4))?; + write!(f, "}}") + } +} + +struct TokensPrettyPrinter<'tokens, 'interner> { + tokens: &'tokens [Token], + interner: &'interner NodeInterner, +} + +impl<'tokens, 'interner> Display for TokensPrettyPrinter<'tokens, 'interner> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + display_tokens(self.tokens, self.interner, 0, f) + } +} + +fn display_tokens( + tokens: &[Token], + interner: &NodeInterner, + indent: usize, + f: &mut std::fmt::Formatter<'_>, +) -> std::fmt::Result { + let mut token_printer = TokenPrettyPrinter::new(interner, indent); + for token in tokens { + token_printer.print(token, f)?; + } + Ok(()) +} + +pub(super) fn tokens_to_string(tokens: Rc>, interner: &NodeInterner) -> String { + let tokens: Vec = tokens.iter().cloned().collect(); + TokensPrettyPrinter { tokens: &tokens, interner }.to_string() +} + +/// Tries to print tokens in a way that it'll be easier for the user to understand a +/// stream of tokens without having to format it themselves. +/// +/// The gist is: +/// - Keep track of the current indent level +/// - When '{' is found, a newline is inserted and the indent is incremented +/// - When '}' is found, a newline is inserted and the indent is decremented +/// - When ';' is found a newline is inserted +/// - When interned values are encountered, they are turned into strings and indented +/// according to the current indentation. +/// +/// There are a few more details that needs to be taken into account: +/// - two consecutive words shouldn't be glued together (as they are separate tokens) +/// - inserting spaces when needed +/// - not inserting extra newlines if possible +/// - ';' shouldn't always insert newlines (this is when it's something like `[Field; 2]`) +struct TokenPrettyPrinter<'interner> { + interner: &'interner NodeInterner, + indent: usize, + last_was_alphanumeric: bool, + last_was_right_brace: bool, + last_was_semicolon: bool, +} + +impl<'interner> TokenPrettyPrinter<'interner> { + fn new(interner: &'interner NodeInterner, indent: usize) -> Self { + Self { + interner, + indent, + last_was_alphanumeric: false, + last_was_right_brace: false, + last_was_semicolon: false, + } + } + + fn print(&mut self, token: &Token, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let last_was_alphanumeric = self.last_was_alphanumeric; + self.last_was_alphanumeric = false; + + // After `}` we usually want a newline... but not always! + if self.last_was_right_brace { + self.last_was_right_brace = false; + + match token { + Token::Keyword(Keyword::Else) => { + // If we have `} else` we don't want a newline + write!(f, " else")?; + self.last_was_alphanumeric = true; + return Ok(()); + } + Token::RightBrace => { + // Because we insert a newline right before `}`, if we have two + // (or more) in a row we don't want extra newlines. + } + _ => { + writeln!(f)?; + self.write_indent(f)?; + } + } + } + + // Heuristic: if we have `; 2` then we assume we are inside something like `[Field; 2]` + // and don't include a newline. + // The only consequence of getting this wrong is that we'll end with two consecutive + // statements in a single line (not a big deal). + if self.last_was_semicolon { + self.last_was_semicolon = false; + + match token { + Token::Int(..) => { + write!(f, " ")?; + } + Token::Ident(ident) => { + if ident.chars().all(|char| char.is_ascii_uppercase()) { + write!(f, " ")?; + } else { + writeln!(f)?; + self.write_indent(f)?; + } + } + Token::RightBrace => { + // We don't want an extra newline in this case + } + _ => { + writeln!(f)?; + self.write_indent(f)?; + } + } + } + + match token { + Token::QuotedType(id) => write!(f, "{}", self.interner.get_quoted_type(*id)), + Token::InternedExpr(id) => { + let value = Value::expression(ExpressionKind::Interned(*id)); + self.print_value(&value, f) + } + Token::InternedStatement(id) => { + let value = Value::statement(StatementKind::Interned(*id)); + self.print_value(&value, f) + } + Token::InternedLValue(id) => { + let value = Value::lvalue(LValue::Interned(*id, Span::default())); + self.print_value(&value, f) + } + Token::InternedUnresolvedTypeData(id) => { + let value = Value::UnresolvedType(UnresolvedTypeData::Interned(*id)); + self.print_value(&value, f) + } + Token::InternedPattern(id) => { + let value = Value::pattern(Pattern::Interned(*id, Span::default())); + self.print_value(&value, f) + } + Token::UnquoteMarker(id) => { + let value = Value::TypedExpr(TypedExpr::ExprId(*id)); + self.print_value(&value, f) + } + Token::Keyword(..) + | Token::Ident(..) + | Token::IntType(..) + | Token::Int(..) + | Token::Bool(..) => { + if last_was_alphanumeric { + write!(f, " ")?; + } + self.last_was_alphanumeric = true; + write!(f, "{token}") + } + Token::Comma => { + write!(f, "{token} ") + } + Token::LeftBrace => { + writeln!(f, " {{")?; + self.indent += 1; + self.write_indent(f) + } + Token::RightBrace => { + self.last_was_right_brace = true; + writeln!(f)?; + self.indent -= 1; + self.write_indent(f)?; + write!(f, "}}") + } + Token::Semicolon => { + self.last_was_semicolon = true; + write!(f, ";") + } + Token::Quote(tokens) => { + if last_was_alphanumeric { + write!(f, " ")?; + } + let tokens = vecmap(&tokens.0, |spanned_token| spanned_token.clone().into_token()); + display_quoted(&tokens, self.indent, self.interner, f) + } + Token::Colon => { + write!(f, "{token} ") + } + Token::Less + | Token::LessEqual + | Token::Greater + | Token::GreaterEqual + | Token::Equal + | Token::NotEqual + | Token::Plus + | Token::Minus + | Token::Star + | Token::Slash + | Token::Percent + | Token::Ampersand + | Token::ShiftLeft + | Token::ShiftRight + | Token::Assign + | Token::Arrow => write!(f, " {token} "), + Token::LeftParen + | Token::RightParen + | Token::LeftBracket + | Token::RightBracket + | Token::Dot + | Token::DoubleColon + | Token::DoubleDot + | Token::Caret + | Token::Pound + | Token::Pipe + | Token::Bang + | Token::DollarSign => { + write!(f, "{token}") + } + Token::Str(..) + | Token::RawStr(..) + | Token::FmtStr(..) + | Token::Whitespace(_) + | Token::LineComment(..) + | Token::BlockComment(..) + | Token::Attribute(..) + | Token::InnerAttribute(..) + | Token::Invalid(_) => { + if last_was_alphanumeric { + write!(f, " ")?; + } + write!(f, "{token}") + } + Token::EOF => Ok(()), + } + } + + fn print_value(&mut self, value: &Value, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let string = value.display(self.interner).to_string(); + for (index, line) in string.lines().enumerate() { + if index > 0 { + writeln!(f)?; + self.write_indent(f)?; + } + line.fmt(f)?; + } + + self.last_was_alphanumeric = string.bytes().all(|byte| byte.is_ascii_alphanumeric()); + self.last_was_right_brace = string.ends_with('}'); + self.last_was_semicolon = string.ends_with(';'); + + Ok(()) + } + + fn write_indent(&mut self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", " ".repeat(self.indent * 4)) + } +} + +impl Value { + pub fn display<'value, 'interner>( + &'value self, + interner: &'interner NodeInterner, + ) -> ValuePrinter<'value, 'interner> { + ValuePrinter { value: self, interner } + } +} + +pub struct ValuePrinter<'value, 'interner> { + value: &'value Value, + interner: &'interner NodeInterner, +} + +impl<'value, 'interner> Display for ValuePrinter<'value, 'interner> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.value { + Value::Unit => write!(f, "()"), + Value::Bool(value) => { + let msg = if *value { "true" } else { "false" }; + write!(f, "{msg}") + } + Value::Field(value) => write!(f, "{value}"), + Value::I8(value) => write!(f, "{value}"), + Value::I16(value) => write!(f, "{value}"), + Value::I32(value) => write!(f, "{value}"), + Value::I64(value) => write!(f, "{value}"), + Value::U1(value) => write!(f, "{value}"), + Value::U8(value) => write!(f, "{value}"), + Value::U16(value) => write!(f, "{value}"), + Value::U32(value) => write!(f, "{value}"), + Value::U64(value) => write!(f, "{value}"), + Value::String(value) => write!(f, "{value}"), + Value::CtString(value) => write!(f, "{value}"), + Value::FormatString(value, _) => write!(f, "{value}"), + Value::Function(..) => write!(f, "(function)"), + Value::Closure(..) => write!(f, "(closure)"), + Value::Tuple(fields) => { + let fields = vecmap(fields, |field| field.display(self.interner).to_string()); + write!(f, "({})", fields.join(", ")) + } + Value::Struct(fields, typ) => { + let typename = match typ.follow_bindings() { + Type::Struct(def, _) => def.borrow().name.to_string(), + other => other.to_string(), + }; + let fields = vecmap(fields, |(name, value)| { + format!("{}: {}", name, value.display(self.interner)) + }); + write!(f, "{typename} {{ {} }}", fields.join(", ")) + } + Value::Pointer(value, _) => write!(f, "&mut {}", value.borrow().display(self.interner)), + Value::Array(values, _) => { + let values = vecmap(values, |value| value.display(self.interner).to_string()); + write!(f, "[{}]", values.join(", ")) + } + Value::Slice(values, _) => { + let values = vecmap(values, |value| value.display(self.interner).to_string()); + write!(f, "&[{}]", values.join(", ")) + } + Value::Quoted(tokens) => display_quoted(tokens, 0, self.interner, f), + Value::StructDefinition(id) => { + let def = self.interner.get_struct(*id); + let def = def.borrow(); + write!(f, "{}", def.name) + } + Value::TraitConstraint(trait_id, generics) => { + let trait_ = self.interner.get_trait(*trait_id); + write!(f, "{}{generics}", trait_.name) + } + Value::TraitDefinition(trait_id) => { + let trait_ = self.interner.get_trait(*trait_id); + write!(f, "{}", trait_.name) + } + Value::TraitImpl(trait_impl_id) => { + let trait_impl = self.interner.get_trait_implementation(*trait_impl_id); + let trait_impl = trait_impl.borrow(); + + let generic_string = + vecmap(&trait_impl.trait_generics, ToString::to_string).join(", "); + let generic_string = if generic_string.is_empty() { + generic_string + } else { + format!("<{}>", generic_string) + }; + + let where_clause = vecmap(&trait_impl.where_clause, |trait_constraint| { + display_trait_constraint(self.interner, trait_constraint) + }); + let where_clause = where_clause.join(", "); + let where_clause = if where_clause.is_empty() { + where_clause + } else { + format!(" where {}", where_clause) + }; + + write!( + f, + "impl {}{} for {}{}", + trait_impl.ident, generic_string, trait_impl.typ, where_clause + ) + } + Value::FunctionDefinition(function_id) => { + write!(f, "{}", self.interner.function_name(function_id)) + } + Value::ModuleDefinition(module_id) => { + if let Some(attributes) = self.interner.try_module_attributes(module_id) { + write!(f, "{}", &attributes.name) + } else { + write!(f, "(crate root)") + } + } + Value::Zeroed(typ) => write!(f, "(zeroed {typ})"), + Value::Type(typ) => write!(f, "{}", typ), + Value::Expr(ExprValue::Expression(expr)) => { + let expr = remove_interned_in_expression_kind(self.interner, expr.clone()); + write!(f, "{}", expr) + } + Value::Expr(ExprValue::Statement(statement)) => { + write!(f, "{}", remove_interned_in_statement_kind(self.interner, statement.clone())) + } + Value::Expr(ExprValue::LValue(lvalue)) => { + write!(f, "{}", remove_interned_in_lvalue(self.interner, lvalue.clone())) + } + Value::Expr(ExprValue::Pattern(pattern)) => { + write!(f, "{}", remove_interned_in_pattern(self.interner, pattern.clone())) + } + Value::TypedExpr(TypedExpr::ExprId(id)) => { + let hir_expr = self.interner.expression(id); + let expr = hir_expr.to_display_ast(self.interner, Span::default()); + write!(f, "{}", expr.kind) + } + Value::TypedExpr(TypedExpr::StmtId(id)) => { + let hir_statement = self.interner.statement(id); + let stmt = hir_statement.to_display_ast(self.interner, Span::default()); + write!(f, "{}", stmt.kind) + } + Value::UnresolvedType(typ) => { + write!(f, "{}", remove_interned_in_unresolved_type_data(self.interner, typ.clone())) + } + } + } +} + +impl Token { + pub fn display<'token, 'interner>( + &'token self, + interner: &'interner NodeInterner, + ) -> TokenPrinter<'token, 'interner> { + TokenPrinter { token: self, interner } + } +} + +pub struct TokenPrinter<'token, 'interner> { + token: &'token Token, + interner: &'interner NodeInterner, +} + +impl<'token, 'interner> Display for TokenPrinter<'token, 'interner> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self.token { + Token::QuotedType(id) => { + write!(f, "{}", self.interner.get_quoted_type(*id)) + } + Token::InternedExpr(id) => { + let value = Value::expression(ExpressionKind::Interned(*id)); + value.display(self.interner).fmt(f) + } + Token::InternedStatement(id) => { + let value = Value::statement(StatementKind::Interned(*id)); + value.display(self.interner).fmt(f) + } + Token::InternedLValue(id) => { + let value = Value::lvalue(LValue::Interned(*id, Span::default())); + value.display(self.interner).fmt(f) + } + Token::InternedUnresolvedTypeData(id) => { + let value = Value::UnresolvedType(UnresolvedTypeData::Interned(*id)); + value.display(self.interner).fmt(f) + } + Token::InternedPattern(id) => { + let value = Value::pattern(Pattern::Interned(*id, Span::default())); + value.display(self.interner).fmt(f) + } + Token::UnquoteMarker(id) => { + let value = Value::TypedExpr(TypedExpr::ExprId(*id)); + value.display(self.interner).fmt(f) + } + other => write!(f, "{other}"), + } + } +} + +fn display_trait_constraint(interner: &NodeInterner, trait_constraint: &TraitConstraint) -> String { + let trait_ = interner.get_trait(trait_constraint.trait_id); + format!("{}: {}{}", trait_constraint.typ, trait_.name, trait_constraint.trait_generics) +} + +// Returns a new Expression where all Interned and Resolved expressions have been turned into non-interned ExpressionKind. +fn remove_interned_in_expression(interner: &NodeInterner, expr: Expression) -> Expression { + Expression { kind: remove_interned_in_expression_kind(interner, expr.kind), span: expr.span } +} + +// Returns a new ExpressionKind where all Interned and Resolved expressions have been turned into non-interned ExpressionKind. +fn remove_interned_in_expression_kind( + interner: &NodeInterner, + expr: ExpressionKind, +) -> ExpressionKind { + match expr { + ExpressionKind::Literal(literal) => { + ExpressionKind::Literal(remove_interned_in_literal(interner, literal)) + } + ExpressionKind::Block(block) => { + let statements = + vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); + ExpressionKind::Block(BlockExpression { statements }) + } + ExpressionKind::Prefix(prefix) => ExpressionKind::Prefix(Box::new(PrefixExpression { + rhs: remove_interned_in_expression(interner, prefix.rhs), + ..*prefix + })), + ExpressionKind::Index(index) => ExpressionKind::Index(Box::new(IndexExpression { + collection: remove_interned_in_expression(interner, index.collection), + index: remove_interned_in_expression(interner, index.index), + })), + ExpressionKind::Call(call) => ExpressionKind::Call(Box::new(CallExpression { + func: Box::new(remove_interned_in_expression(interner, *call.func)), + arguments: vecmap(call.arguments, |arg| remove_interned_in_expression(interner, arg)), + ..*call + })), + ExpressionKind::MethodCall(call) => { + ExpressionKind::MethodCall(Box::new(MethodCallExpression { + object: remove_interned_in_expression(interner, call.object), + arguments: vecmap(call.arguments, |arg| { + remove_interned_in_expression(interner, arg) + }), + ..*call + })) + } + ExpressionKind::Constructor(constructor) => { + ExpressionKind::Constructor(Box::new(ConstructorExpression { + fields: vecmap(constructor.fields, |(name, expr)| { + (name, remove_interned_in_expression(interner, expr)) + }), + ..*constructor + })) + } + ExpressionKind::MemberAccess(member_access) => { + ExpressionKind::MemberAccess(Box::new(MemberAccessExpression { + lhs: remove_interned_in_expression(interner, member_access.lhs), + ..*member_access + })) + } + ExpressionKind::Cast(cast) => ExpressionKind::Cast(Box::new(CastExpression { + lhs: remove_interned_in_expression(interner, cast.lhs), + ..*cast + })), + ExpressionKind::Infix(infix) => ExpressionKind::Infix(Box::new(InfixExpression { + lhs: remove_interned_in_expression(interner, infix.lhs), + rhs: remove_interned_in_expression(interner, infix.rhs), + ..*infix + })), + ExpressionKind::If(if_expr) => ExpressionKind::If(Box::new(IfExpression { + condition: remove_interned_in_expression(interner, if_expr.condition), + consequence: remove_interned_in_expression(interner, if_expr.consequence), + alternative: if_expr + .alternative + .map(|alternative| remove_interned_in_expression(interner, alternative)), + })), + ExpressionKind::Variable(_) => expr, + ExpressionKind::Tuple(expressions) => ExpressionKind::Tuple(vecmap(expressions, |expr| { + remove_interned_in_expression(interner, expr) + })), + ExpressionKind::Lambda(lambda) => ExpressionKind::Lambda(Box::new(Lambda { + body: remove_interned_in_expression(interner, lambda.body), + ..*lambda + })), + ExpressionKind::Parenthesized(expr) => { + ExpressionKind::Parenthesized(Box::new(remove_interned_in_expression(interner, *expr))) + } + ExpressionKind::Quote(_) => expr, + ExpressionKind::Unquote(expr) => { + ExpressionKind::Unquote(Box::new(remove_interned_in_expression(interner, *expr))) + } + ExpressionKind::Comptime(block, span) => { + let statements = + vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); + ExpressionKind::Comptime(BlockExpression { statements }, span) + } + ExpressionKind::Unsafe(block, span) => { + let statements = + vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); + ExpressionKind::Unsafe(BlockExpression { statements }, span) + } + ExpressionKind::AsTraitPath(mut path) => { + path.typ = remove_interned_in_unresolved_type(interner, path.typ); + path.trait_generics = + remove_interned_in_generic_type_args(interner, path.trait_generics); + ExpressionKind::AsTraitPath(path) + } + ExpressionKind::TypePath(mut path) => { + path.typ = remove_interned_in_unresolved_type(interner, path.typ); + path.turbofish = remove_interned_in_generic_type_args(interner, path.turbofish); + ExpressionKind::TypePath(path) + } + ExpressionKind::Resolved(id) => { + let expr = interner.expression(&id); + expr.to_display_ast(interner, Span::default()).kind + } + ExpressionKind::Interned(id) => { + let expr = interner.get_expression_kind(id).clone(); + remove_interned_in_expression_kind(interner, expr) + } + ExpressionKind::Error => expr, + ExpressionKind::InternedStatement(id) => remove_interned_in_statement_expr(interner, id), + } +} + +fn remove_interned_in_statement_expr( + interner: &NodeInterner, + id: InternedStatementKind, +) -> ExpressionKind { + let expr = match interner.get_statement_kind(id).clone() { + StatementKind::Expression(expr) | StatementKind::Semi(expr) => expr.kind, + StatementKind::Interned(id) => remove_interned_in_statement_expr(interner, id), + _ => ExpressionKind::Error, + }; + remove_interned_in_expression_kind(interner, expr) +} + +fn remove_interned_in_literal(interner: &NodeInterner, literal: Literal) -> Literal { + match literal { + Literal::Array(array_literal) => { + Literal::Array(remove_interned_in_array_literal(interner, array_literal)) + } + Literal::Slice(array_literal) => { + Literal::Array(remove_interned_in_array_literal(interner, array_literal)) + } + Literal::Bool(_) + | Literal::Integer(_, _) + | Literal::Str(_) + | Literal::RawStr(_, _) + | Literal::FmtStr(_) + | Literal::Unit => literal, + } +} + +fn remove_interned_in_array_literal( + interner: &NodeInterner, + literal: ArrayLiteral, +) -> ArrayLiteral { + match literal { + ArrayLiteral::Standard(expressions) => { + ArrayLiteral::Standard(vecmap(expressions, |expr| { + remove_interned_in_expression(interner, expr) + })) + } + ArrayLiteral::Repeated { repeated_element, length } => ArrayLiteral::Repeated { + repeated_element: Box::new(remove_interned_in_expression(interner, *repeated_element)), + length: Box::new(remove_interned_in_expression(interner, *length)), + }, + } +} + +// Returns a new Statement where all Interned statements have been turned into non-interned StatementKind. +fn remove_interned_in_statement(interner: &NodeInterner, statement: Statement) -> Statement { + Statement { + kind: remove_interned_in_statement_kind(interner, statement.kind), + span: statement.span, + } +} + +// Returns a new StatementKind where all Interned statements have been turned into non-interned StatementKind. +fn remove_interned_in_statement_kind( + interner: &NodeInterner, + statement: StatementKind, +) -> StatementKind { + match statement { + StatementKind::Let(let_statement) => StatementKind::Let(LetStatement { + pattern: remove_interned_in_pattern(interner, let_statement.pattern), + expression: remove_interned_in_expression(interner, let_statement.expression), + r#type: remove_interned_in_unresolved_type(interner, let_statement.r#type), + ..let_statement + }), + StatementKind::Constrain(constrain) => StatementKind::Constrain(ConstrainStatement { + arguments: vecmap(constrain.arguments, |expr| { + remove_interned_in_expression(interner, expr) + }), + ..constrain + }), + StatementKind::Expression(expr) => { + StatementKind::Expression(remove_interned_in_expression(interner, expr)) + } + StatementKind::Assign(assign) => StatementKind::Assign(AssignStatement { + lvalue: assign.lvalue, + expression: remove_interned_in_expression(interner, assign.expression), + }), + StatementKind::For(for_loop) => StatementKind::For(ForLoopStatement { + range: match for_loop.range { + ForRange::Range(from, to) => ForRange::Range( + remove_interned_in_expression(interner, from), + remove_interned_in_expression(interner, to), + ), + ForRange::Array(expr) => { + ForRange::Array(remove_interned_in_expression(interner, expr)) + } + }, + block: remove_interned_in_expression(interner, for_loop.block), + ..for_loop + }), + StatementKind::Comptime(statement) => { + StatementKind::Comptime(Box::new(remove_interned_in_statement(interner, *statement))) + } + StatementKind::Semi(expr) => { + StatementKind::Semi(remove_interned_in_expression(interner, expr)) + } + StatementKind::Interned(id) => { + let statement = interner.get_statement_kind(id).clone(); + remove_interned_in_statement_kind(interner, statement) + } + StatementKind::Break | StatementKind::Continue | StatementKind::Error => statement, + } +} + +// Returns a new LValue where all Interned LValues have been turned into LValue. +fn remove_interned_in_lvalue(interner: &NodeInterner, lvalue: LValue) -> LValue { + match lvalue { + LValue::Ident(_) => lvalue, + LValue::MemberAccess { object, field_name, span } => LValue::MemberAccess { + object: Box::new(remove_interned_in_lvalue(interner, *object)), + field_name, + span, + }, + LValue::Index { array, index, span } => LValue::Index { + array: Box::new(remove_interned_in_lvalue(interner, *array)), + index: remove_interned_in_expression(interner, index), + span, + }, + LValue::Dereference(lvalue, span) => { + LValue::Dereference(Box::new(remove_interned_in_lvalue(interner, *lvalue)), span) + } + LValue::Interned(id, span) => { + let lvalue = interner.get_lvalue(id, span); + remove_interned_in_lvalue(interner, lvalue) + } + } +} + +fn remove_interned_in_unresolved_type( + interner: &NodeInterner, + typ: UnresolvedType, +) -> UnresolvedType { + UnresolvedType { + typ: remove_interned_in_unresolved_type_data(interner, typ.typ), + span: typ.span, + } +} + +fn remove_interned_in_unresolved_type_data( + interner: &NodeInterner, + typ: UnresolvedTypeData, +) -> UnresolvedTypeData { + match typ { + UnresolvedTypeData::Array(expr, typ) => UnresolvedTypeData::Array( + expr, + Box::new(remove_interned_in_unresolved_type(interner, *typ)), + ), + UnresolvedTypeData::Slice(typ) => { + UnresolvedTypeData::Slice(Box::new(remove_interned_in_unresolved_type(interner, *typ))) + } + UnresolvedTypeData::FormatString(expr, typ) => UnresolvedTypeData::FormatString( + expr, + Box::new(remove_interned_in_unresolved_type(interner, *typ)), + ), + UnresolvedTypeData::Parenthesized(typ) => UnresolvedTypeData::Parenthesized(Box::new( + remove_interned_in_unresolved_type(interner, *typ), + )), + UnresolvedTypeData::Named(path, generic_type_args, is_synthesized) => { + UnresolvedTypeData::Named( + path, + remove_interned_in_generic_type_args(interner, generic_type_args), + is_synthesized, + ) + } + UnresolvedTypeData::TraitAsType(path, generic_type_args) => { + UnresolvedTypeData::TraitAsType( + path, + remove_interned_in_generic_type_args(interner, generic_type_args), + ) + } + UnresolvedTypeData::MutableReference(typ) => UnresolvedTypeData::MutableReference( + Box::new(remove_interned_in_unresolved_type(interner, *typ)), + ), + UnresolvedTypeData::Tuple(types) => UnresolvedTypeData::Tuple(vecmap(types, |typ| { + remove_interned_in_unresolved_type(interner, typ) + })), + UnresolvedTypeData::Function(arg_types, ret_type, env_type, unconstrained) => { + UnresolvedTypeData::Function( + vecmap(arg_types, |typ| remove_interned_in_unresolved_type(interner, typ)), + Box::new(remove_interned_in_unresolved_type(interner, *ret_type)), + Box::new(remove_interned_in_unresolved_type(interner, *env_type)), + unconstrained, + ) + } + UnresolvedTypeData::AsTraitPath(as_trait_path) => { + UnresolvedTypeData::AsTraitPath(Box::new(AsTraitPath { + typ: remove_interned_in_unresolved_type(interner, as_trait_path.typ), + trait_generics: remove_interned_in_generic_type_args( + interner, + as_trait_path.trait_generics, + ), + ..*as_trait_path + })) + } + UnresolvedTypeData::Interned(id) => interner.get_unresolved_type_data(id).clone(), + UnresolvedTypeData::FieldElement + | UnresolvedTypeData::Integer(_, _) + | UnresolvedTypeData::Bool + | UnresolvedTypeData::Unit + | UnresolvedTypeData::String(_) + | UnresolvedTypeData::Resolved(_) + | UnresolvedTypeData::Quoted(_) + | UnresolvedTypeData::Expression(_) + | UnresolvedTypeData::Unspecified + | UnresolvedTypeData::Error => typ, + } +} + +fn remove_interned_in_generic_type_args( + interner: &NodeInterner, + args: GenericTypeArgs, +) -> GenericTypeArgs { + GenericTypeArgs { + ordered_args: vecmap(args.ordered_args, |typ| { + remove_interned_in_unresolved_type(interner, typ) + }), + named_args: vecmap(args.named_args, |(name, typ)| { + (name, remove_interned_in_unresolved_type(interner, typ)) + }), + } +} + +// Returns a new Pattern where all Interned Patterns have been turned into Pattern. +fn remove_interned_in_pattern(interner: &NodeInterner, pattern: Pattern) -> Pattern { + match pattern { + Pattern::Identifier(_) => pattern, + Pattern::Mutable(pattern, span, is_synthesized) => Pattern::Mutable( + Box::new(remove_interned_in_pattern(interner, *pattern)), + span, + is_synthesized, + ), + Pattern::Tuple(patterns, span) => Pattern::Tuple( + vecmap(patterns, |pattern| remove_interned_in_pattern(interner, pattern)), + span, + ), + Pattern::Struct(path, patterns, span) => { + let patterns = vecmap(patterns, |(name, pattern)| { + (name, remove_interned_in_pattern(interner, pattern)) + }); + Pattern::Struct(path, patterns, span) + } + Pattern::Interned(id, _) => interner.get_pattern(id).clone(), + } +} diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/errors.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/errors.rs index 0cb2b37e273..5217bbd1e71 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/errors.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/errors.rs @@ -5,12 +5,10 @@ use crate::{ ast::TraitBound, hir::{def_collector::dc_crate::CompilationError, type_check::NoMatchingImplFoundError}, parser::ParserError, - token::Token, Type, }; use acvm::{acir::AcirField, BlackBoxResolutionError, FieldElement}; use fm::FileId; -use iter_extended::vecmap; use noirc_errors::{CustomDiagnostic, Location}; /// The possible errors that can halt the interpreter. @@ -145,7 +143,7 @@ pub enum InterpreterError { }, FailedToParseMacro { error: ParserError, - tokens: Rc>, + tokens: String, rule: &'static str, file: FileId, }, @@ -488,10 +486,9 @@ impl<'a> From<&'a InterpreterError> for CustomDiagnostic { InterpreterError::DebugEvaluateComptime { diagnostic, .. } => diagnostic.clone(), InterpreterError::FailedToParseMacro { error, tokens, rule, file: _ } => { let message = format!("Failed to parse macro's token stream into {rule}"); - let tokens = vecmap(tokens.iter(), ToString::to_string).join(" "); - // 10 is an aribtrary number of tokens here chosen to fit roughly onto one line - let token_stream = if tokens.len() > 10 { + // If it's less than 48 chars, the error message fits in a single line (less than 80 chars total) + let token_stream = if tokens.len() <= 48 && !tokens.contains('\n') { format!("The resulting token stream was: {tokens}") } else { format!( diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/hir_to_display_ast.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/hir_to_display_ast.rs index 4a159c682b7..972826f5b7c 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/hir_to_display_ast.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/hir_to_display_ast.rs @@ -33,10 +33,17 @@ impl HirStatement { } HirStatement::Constrain(constrain) => { let expr = constrain.0.to_display_ast(interner); - let message = constrain.2.map(|message| message.to_display_ast(interner)); + let mut arguments = vec![expr]; + if let Some(message) = constrain.2 { + arguments.push(message.to_display_ast(interner)); + } // TODO: Find difference in usage between Assert & AssertEq - StatementKind::Constrain(ConstrainStatement(expr, message, ConstrainKind::Assert)) + StatementKind::Constrain(ConstrainStatement { + kind: ConstrainKind::Assert, + arguments, + span, + }) } HirStatement::Assign(assign) => StatementKind::Assign(AssignStatement { lvalue: assign.lvalue.to_display_ast(interner), diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs index 04cd54ca78a..dc6a2cec975 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin.rs @@ -146,7 +146,7 @@ impl<'local, 'context> Interpreter<'local, 'context> { "modulus_le_bits" => modulus_le_bits(arguments, location), "modulus_le_bytes" => modulus_le_bytes(arguments, location), "modulus_num_bits" => modulus_num_bits(arguments, location), - "quoted_as_expr" => quoted_as_expr(arguments, return_type, location), + "quoted_as_expr" => quoted_as_expr(interner, arguments, return_type, location), "quoted_as_module" => quoted_as_module(self, arguments, return_type, location), "quoted_as_trait_constraint" => quoted_as_trait_constraint(self, arguments, location), "quoted_as_type" => quoted_as_type(self, arguments, location), @@ -672,6 +672,7 @@ fn slice_insert( // fn as_expr(quoted: Quoted) -> Option fn quoted_as_expr( + interner: &NodeInterner, arguments: Vec<(Value, Location)>, return_type: Type, location: Location, @@ -684,7 +685,7 @@ fn quoted_as_expr( let parser = choice((expr_parser, statement_parser, lvalue_parser)); let parser = parser.then_ignore(just(Token::Semicolon).or_not()); - let expr = parse(argument, parser, "an expression").ok(); + let expr = parse(interner, argument, parser, "an expression").ok(); option(return_type, expr) } @@ -698,7 +699,9 @@ fn quoted_as_module( ) -> IResult { let argument = check_one_argument(arguments, location)?; - let path = parse(argument, parser::path_no_turbofish(), "a path").ok(); + let path = + parse(interpreter.elaborator.interner, argument, parser::path_no_turbofish(), "a path") + .ok(); let option_value = path.and_then(|path| { let module = interpreter .elaborate_in_function(interpreter.current_function, |elaborator| { @@ -717,7 +720,12 @@ fn quoted_as_trait_constraint( location: Location, ) -> IResult { let argument = check_one_argument(arguments, location)?; - let trait_bound = parse(argument, parser::trait_bound(), "a trait constraint")?; + let trait_bound = parse( + interpreter.elaborator.interner, + argument, + parser::trait_bound(), + "a trait constraint", + )?; let bound = interpreter .elaborate_in_function(interpreter.current_function, |elaborator| { elaborator.resolve_trait_bound(&trait_bound, Type::Unit) @@ -734,7 +742,7 @@ fn quoted_as_type( location: Location, ) -> IResult { let argument = check_one_argument(arguments, location)?; - let typ = parse(argument, parser::parse_type(), "a type")?; + let typ = parse(interpreter.elaborator.interner, argument, parser::parse_type(), "a type")?; let typ = interpreter .elaborate_in_function(interpreter.current_function, |elab| elab.resolve_type(typ)); Ok(Value::Type(typ)) @@ -1232,9 +1240,17 @@ fn expr_as_assert( location: Location, ) -> IResult { expr_as(interner, arguments, return_type.clone(), location, |expr| { - if let ExprValue::Statement(StatementKind::Constrain(constrain)) = expr { - if constrain.2 == ConstrainKind::Assert { - let predicate = Value::expression(constrain.0.kind); + if let ExprValue::Statement(StatementKind::Constrain(mut constrain)) = expr { + if constrain.kind == ConstrainKind::Assert + && !constrain.arguments.is_empty() + && constrain.arguments.len() <= 2 + { + let (message, predicate) = if constrain.arguments.len() == 1 { + (None, constrain.arguments.pop().unwrap()) + } else { + (Some(constrain.arguments.pop().unwrap()), constrain.arguments.pop().unwrap()) + }; + let predicate = Value::expression(predicate.kind); let option_type = extract_option_generic_type(return_type); let Type::Tuple(mut tuple_types) = option_type else { @@ -1243,7 +1259,7 @@ fn expr_as_assert( assert_eq!(tuple_types.len(), 2); let option_type = tuple_types.pop().unwrap(); - let message = constrain.1.map(|message| Value::expression(message.kind)); + let message = message.map(|msg| Value::expression(msg.kind)); let message = option(option_type, message).ok()?; Some(Value::Tuple(vec![predicate, message])) @@ -1264,14 +1280,23 @@ fn expr_as_assert_eq( location: Location, ) -> IResult { expr_as(interner, arguments, return_type.clone(), location, |expr| { - if let ExprValue::Statement(StatementKind::Constrain(constrain)) = expr { - if constrain.2 == ConstrainKind::AssertEq { - let ExpressionKind::Infix(infix) = constrain.0.kind else { - panic!("Expected AssertEq constrain statement to have an infix expression"); + if let ExprValue::Statement(StatementKind::Constrain(mut constrain)) = expr { + if constrain.kind == ConstrainKind::AssertEq + && constrain.arguments.len() >= 2 + && constrain.arguments.len() <= 3 + { + let (message, rhs, lhs) = if constrain.arguments.len() == 2 { + (None, constrain.arguments.pop().unwrap(), constrain.arguments.pop().unwrap()) + } else { + ( + Some(constrain.arguments.pop().unwrap()), + constrain.arguments.pop().unwrap(), + constrain.arguments.pop().unwrap(), + ) }; - let lhs = Value::expression(infix.lhs.kind); - let rhs = Value::expression(infix.rhs.kind); + let lhs = Value::expression(lhs.kind); + let rhs = Value::expression(rhs.kind); let option_type = extract_option_generic_type(return_type); let Type::Tuple(mut tuple_types) = option_type else { @@ -1280,7 +1305,7 @@ fn expr_as_assert_eq( assert_eq!(tuple_types.len(), 3); let option_type = tuple_types.pop().unwrap(); - let message = constrain.1.map(|message| Value::expression(message.kind)); + let message = message.map(|message| Value::expression(message.kind)); let message = option(option_type, message).ok()?; Some(Value::Tuple(vec![lhs, rhs, message])) @@ -2301,6 +2326,7 @@ fn function_def_set_parameters( )?; let parameter_type = get_type((tuple.pop().unwrap(), parameters_argument_location))?; let parameter_pattern = parse( + interpreter.elaborator.interner, (tuple.pop().unwrap(), parameters_argument_location), parser::pattern(), "a pattern", @@ -2403,7 +2429,8 @@ fn module_add_item( let module_data = interpreter.elaborator.get_module(module_id); let parser = parser::top_level_items(); - let top_level_statements = parse(item, parser, "a top-level item")?; + let top_level_statements = + parse(interpreter.elaborator.interner, item, parser, "a top-level item")?; interpreter.elaborate_in_module(module_id, module_data.location.file, |elaborator| { let mut generated_items = CollectedItems::default(); diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin/builtin_helpers.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin/builtin_helpers.rs index 5fe5447da6a..20303e49e15 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin/builtin_helpers.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/interpreter/builtin/builtin_helpers.rs @@ -4,6 +4,7 @@ use std::{hash::Hasher, rc::Rc}; use acvm::FieldElement; use noirc_errors::Location; +use crate::hir::comptime::display::tokens_to_string; use crate::lexer::Lexer; use crate::{ ast::{ @@ -403,6 +404,7 @@ pub(super) fn lex(input: &str) -> Vec { } pub(super) fn parse( + interner: &NodeInterner, (value, location): (Value, Location), parser: impl NoirParser, rule: &'static str, @@ -410,18 +412,20 @@ pub(super) fn parse( let parser = parser.then_ignore(chumsky::primitive::end()); let tokens = get_quoted((value, location))?; let quoted = add_token_spans(tokens.clone(), location.span); - parse_tokens(tokens, quoted, location, parser, rule) + parse_tokens(tokens, quoted, interner, location, parser, rule) } pub(super) fn parse_tokens( tokens: Rc>, quoted: Tokens, + interner: &NodeInterner, location: Location, parser: impl NoirParser, rule: &'static str, ) -> IResult { parser.parse(quoted).map_err(|mut errors| { let error = errors.swap_remove(0); + let tokens = tokens_to_string(tokens, interner); InterpreterError::FailedToParseMacro { error, tokens, rule, file: location.file } }) } diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/mod.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/mod.rs index 16090c64174..2e2753001b4 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/mod.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/mod.rs @@ -1,3 +1,4 @@ +mod display; mod errors; mod hir_to_display_ast; mod interpreter; diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/value.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/value.rs index 4d0787628cd..f01e188e498 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/value.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/comptime/value.rs @@ -1,4 +1,4 @@ -use std::{borrow::Cow, fmt::Display, rc::Rc, vec}; +use std::{borrow::Cow, rc::Rc, vec}; use acvm::{AcirField, FieldElement}; use chumsky::Parser; @@ -9,29 +9,26 @@ use strum_macros::Display; use crate::{ ast::{ - ArrayLiteral, AsTraitPath, AssignStatement, BlockExpression, CallExpression, - CastExpression, ConstrainStatement, ConstructorExpression, ForLoopStatement, ForRange, - GenericTypeArgs, Ident, IfExpression, IndexExpression, InfixExpression, IntegerBitSize, - LValue, Lambda, LetStatement, MemberAccessExpression, MethodCallExpression, Pattern, - PrefixExpression, Signedness, Statement, StatementKind, UnresolvedType, UnresolvedTypeData, + ArrayLiteral, BlockExpression, ConstructorExpression, Ident, IntegerBitSize, LValue, + Pattern, Signedness, Statement, StatementKind, UnresolvedType, UnresolvedTypeData, }, hir::{def_map::ModuleId, type_check::generics::TraitGenerics}, - hir_def::{ - expr::{HirArrayLiteral, HirConstructorExpression, HirIdent, HirLambda, ImplKind}, - traits::TraitConstraint, - }, + hir_def::expr::{HirArrayLiteral, HirConstructorExpression, HirIdent, HirLambda, ImplKind}, macros_api::{ Expression, ExpressionKind, HirExpression, HirLiteral, Literal, NodeInterner, Path, StructId, }, - node_interner::{ExprId, FuncId, InternedStatementKind, StmtId, TraitId, TraitImplId}, + node_interner::{ExprId, FuncId, StmtId, TraitId, TraitImplId}, parser::{self, NoirParser, TopLevelStatement}, token::{SpannedToken, Token, Tokens}, Kind, QuotedType, Shared, Type, TypeBindings, }; use rustc_hash::FxHashMap as HashMap; -use super::errors::{IResult, InterpreterError}; +use super::{ + display::tokens_to_string, + errors::{IResult, InterpreterError}, +}; #[derive(Debug, Clone, PartialEq, Eq)] pub enum Value { @@ -270,6 +267,7 @@ impl Value { let error = errors.swap_remove(0); let file = location.file; let rule = "an expression"; + let tokens = tokens_to_string(tokens, interner); Err(InterpreterError::FailedToParseMacro { error, file, tokens, rule }) } }; @@ -526,8 +524,11 @@ impl Value { location: Location, interner: &NodeInterner, ) -> IResult> { + let parser = parser::top_level_items(); match self { - Value::Quoted(tokens) => parse_tokens(tokens, parser::top_level_items(), location), + Value::Quoted(tokens) => { + parse_tokens(tokens, interner, parser, location, "top-level item") + } _ => { let typ = self.get_type().into_owned(); let value = self.display(interner).to_string(); @@ -535,13 +536,6 @@ impl Value { } } } - - pub fn display<'value, 'interner>( - &'value self, - interner: &'interner NodeInterner, - ) -> ValuePrinter<'value, 'interner> { - ValuePrinter { value: self, interner } - } } /// Unwraps an Rc value without cloning the inner value if the reference count is 1. Clones otherwise. @@ -551,16 +545,18 @@ pub(crate) fn unwrap_rc(rc: Rc) -> T { fn parse_tokens( tokens: Rc>, + interner: &NodeInterner, parser: impl NoirParser, location: Location, + rule: &'static str, ) -> IResult { let parser = parser.then_ignore(chumsky::primitive::end()); match parser.parse(add_token_spans(tokens.clone(), location.span)) { Ok(expr) => Ok(expr), Err(mut errors) => { let error = errors.swap_remove(0); - let rule = "an expression"; let file = location.file; + let tokens = tokens_to_string(tokens, interner); Err(InterpreterError::FailedToParseMacro { error, file, tokens, rule }) } } @@ -570,564 +566,3 @@ pub(crate) fn add_token_spans(tokens: Rc>, span: Span) -> Tokens { let tokens = unwrap_rc(tokens); Tokens(vecmap(tokens, |token| SpannedToken::new(token, span))) } - -pub struct ValuePrinter<'value, 'interner> { - value: &'value Value, - interner: &'interner NodeInterner, -} - -impl<'value, 'interner> Display for ValuePrinter<'value, 'interner> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.value { - Value::Unit => write!(f, "()"), - Value::Bool(value) => { - let msg = if *value { "true" } else { "false" }; - write!(f, "{msg}") - } - Value::Field(value) => write!(f, "{value}"), - Value::I8(value) => write!(f, "{value}"), - Value::I16(value) => write!(f, "{value}"), - Value::I32(value) => write!(f, "{value}"), - Value::I64(value) => write!(f, "{value}"), - Value::U1(value) => write!(f, "{value}"), - Value::U8(value) => write!(f, "{value}"), - Value::U16(value) => write!(f, "{value}"), - Value::U32(value) => write!(f, "{value}"), - Value::U64(value) => write!(f, "{value}"), - Value::String(value) => write!(f, "{value}"), - Value::CtString(value) => write!(f, "{value}"), - Value::FormatString(value, _) => write!(f, "{value}"), - Value::Function(..) => write!(f, "(function)"), - Value::Closure(..) => write!(f, "(closure)"), - Value::Tuple(fields) => { - let fields = vecmap(fields, |field| field.display(self.interner).to_string()); - write!(f, "({})", fields.join(", ")) - } - Value::Struct(fields, typ) => { - let typename = match typ.follow_bindings() { - Type::Struct(def, _) => def.borrow().name.to_string(), - other => other.to_string(), - }; - let fields = vecmap(fields, |(name, value)| { - format!("{}: {}", name, value.display(self.interner)) - }); - write!(f, "{typename} {{ {} }}", fields.join(", ")) - } - Value::Pointer(value, _) => write!(f, "&mut {}", value.borrow().display(self.interner)), - Value::Array(values, _) => { - let values = vecmap(values, |value| value.display(self.interner).to_string()); - write!(f, "[{}]", values.join(", ")) - } - Value::Slice(values, _) => { - let values = vecmap(values, |value| value.display(self.interner).to_string()); - write!(f, "&[{}]", values.join(", ")) - } - Value::Quoted(tokens) => { - write!(f, "quote {{")?; - for token in tokens.iter() { - write!(f, " ")?; - token.display(self.interner).fmt(f)?; - } - write!(f, " }}") - } - Value::StructDefinition(id) => { - let def = self.interner.get_struct(*id); - let def = def.borrow(); - write!(f, "{}", def.name) - } - Value::TraitConstraint(trait_id, generics) => { - let trait_ = self.interner.get_trait(*trait_id); - write!(f, "{}{generics}", trait_.name) - } - Value::TraitDefinition(trait_id) => { - let trait_ = self.interner.get_trait(*trait_id); - write!(f, "{}", trait_.name) - } - Value::TraitImpl(trait_impl_id) => { - let trait_impl = self.interner.get_trait_implementation(*trait_impl_id); - let trait_impl = trait_impl.borrow(); - - let generic_string = - vecmap(&trait_impl.trait_generics, ToString::to_string).join(", "); - let generic_string = if generic_string.is_empty() { - generic_string - } else { - format!("<{}>", generic_string) - }; - - let where_clause = vecmap(&trait_impl.where_clause, |trait_constraint| { - display_trait_constraint(self.interner, trait_constraint) - }); - let where_clause = where_clause.join(", "); - let where_clause = if where_clause.is_empty() { - where_clause - } else { - format!(" where {}", where_clause) - }; - - write!( - f, - "impl {}{} for {}{}", - trait_impl.ident, generic_string, trait_impl.typ, where_clause - ) - } - Value::FunctionDefinition(function_id) => { - write!(f, "{}", self.interner.function_name(function_id)) - } - Value::ModuleDefinition(module_id) => { - if let Some(attributes) = self.interner.try_module_attributes(module_id) { - write!(f, "{}", &attributes.name) - } else { - write!(f, "(crate root)") - } - } - Value::Zeroed(typ) => write!(f, "(zeroed {typ})"), - Value::Type(typ) => write!(f, "{}", typ), - Value::Expr(ExprValue::Expression(expr)) => { - write!(f, "{}", remove_interned_in_expression_kind(self.interner, expr.clone())) - } - Value::Expr(ExprValue::Statement(statement)) => { - write!(f, "{}", remove_interned_in_statement_kind(self.interner, statement.clone())) - } - Value::Expr(ExprValue::LValue(lvalue)) => { - write!(f, "{}", remove_interned_in_lvalue(self.interner, lvalue.clone())) - } - Value::Expr(ExprValue::Pattern(pattern)) => { - write!(f, "{}", remove_interned_in_pattern(self.interner, pattern.clone())) - } - Value::TypedExpr(TypedExpr::ExprId(id)) => { - let hir_expr = self.interner.expression(id); - let expr = hir_expr.to_display_ast(self.interner, Span::default()); - write!(f, "{}", expr.kind) - } - Value::TypedExpr(TypedExpr::StmtId(id)) => { - let hir_statement = self.interner.statement(id); - let stmt = hir_statement.to_display_ast(self.interner, Span::default()); - write!(f, "{}", stmt.kind) - } - Value::UnresolvedType(typ) => { - write!(f, "{}", remove_interned_in_unresolved_type_data(self.interner, typ.clone())) - } - } - } -} - -impl Token { - pub fn display<'token, 'interner>( - &'token self, - interner: &'interner NodeInterner, - ) -> TokenPrinter<'token, 'interner> { - TokenPrinter { token: self, interner } - } -} - -pub struct TokenPrinter<'token, 'interner> { - token: &'token Token, - interner: &'interner NodeInterner, -} - -impl<'token, 'interner> Display for TokenPrinter<'token, 'interner> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.token { - Token::QuotedType(id) => { - write!(f, "{}", self.interner.get_quoted_type(*id)) - } - Token::InternedExpr(id) => { - let value = Value::expression(ExpressionKind::Interned(*id)); - value.display(self.interner).fmt(f) - } - Token::InternedStatement(id) => { - let value = Value::statement(StatementKind::Interned(*id)); - value.display(self.interner).fmt(f) - } - Token::InternedLValue(id) => { - let value = Value::lvalue(LValue::Interned(*id, Span::default())); - value.display(self.interner).fmt(f) - } - Token::InternedUnresolvedTypeData(id) => { - let value = Value::UnresolvedType(UnresolvedTypeData::Interned(*id)); - value.display(self.interner).fmt(f) - } - Token::InternedPattern(id) => { - let value = Value::pattern(Pattern::Interned(*id, Span::default())); - value.display(self.interner).fmt(f) - } - Token::UnquoteMarker(id) => { - let value = Value::TypedExpr(TypedExpr::ExprId(*id)); - value.display(self.interner).fmt(f) - } - other => write!(f, "{other}"), - } - } -} - -fn display_trait_constraint(interner: &NodeInterner, trait_constraint: &TraitConstraint) -> String { - let trait_ = interner.get_trait(trait_constraint.trait_id); - format!("{}: {}{}", trait_constraint.typ, trait_.name, trait_constraint.trait_generics) -} - -// Returns a new Expression where all Interned and Resolved expressions have been turned into non-interned ExpressionKind. -fn remove_interned_in_expression(interner: &NodeInterner, expr: Expression) -> Expression { - Expression { kind: remove_interned_in_expression_kind(interner, expr.kind), span: expr.span } -} - -// Returns a new ExpressionKind where all Interned and Resolved expressions have been turned into non-interned ExpressionKind. -fn remove_interned_in_expression_kind( - interner: &NodeInterner, - expr: ExpressionKind, -) -> ExpressionKind { - match expr { - ExpressionKind::Literal(literal) => { - ExpressionKind::Literal(remove_interned_in_literal(interner, literal)) - } - ExpressionKind::Block(block) => { - let statements = - vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); - ExpressionKind::Block(BlockExpression { statements }) - } - ExpressionKind::Prefix(prefix) => ExpressionKind::Prefix(Box::new(PrefixExpression { - rhs: remove_interned_in_expression(interner, prefix.rhs), - ..*prefix - })), - ExpressionKind::Index(index) => ExpressionKind::Index(Box::new(IndexExpression { - collection: remove_interned_in_expression(interner, index.collection), - index: remove_interned_in_expression(interner, index.index), - })), - ExpressionKind::Call(call) => ExpressionKind::Call(Box::new(CallExpression { - func: Box::new(remove_interned_in_expression(interner, *call.func)), - arguments: vecmap(call.arguments, |arg| remove_interned_in_expression(interner, arg)), - ..*call - })), - ExpressionKind::MethodCall(call) => { - ExpressionKind::MethodCall(Box::new(MethodCallExpression { - object: remove_interned_in_expression(interner, call.object), - arguments: vecmap(call.arguments, |arg| { - remove_interned_in_expression(interner, arg) - }), - ..*call - })) - } - ExpressionKind::Constructor(constructor) => { - ExpressionKind::Constructor(Box::new(ConstructorExpression { - fields: vecmap(constructor.fields, |(name, expr)| { - (name, remove_interned_in_expression(interner, expr)) - }), - ..*constructor - })) - } - ExpressionKind::MemberAccess(member_access) => { - ExpressionKind::MemberAccess(Box::new(MemberAccessExpression { - lhs: remove_interned_in_expression(interner, member_access.lhs), - ..*member_access - })) - } - ExpressionKind::Cast(cast) => ExpressionKind::Cast(Box::new(CastExpression { - lhs: remove_interned_in_expression(interner, cast.lhs), - ..*cast - })), - ExpressionKind::Infix(infix) => ExpressionKind::Infix(Box::new(InfixExpression { - lhs: remove_interned_in_expression(interner, infix.lhs), - rhs: remove_interned_in_expression(interner, infix.rhs), - ..*infix - })), - ExpressionKind::If(if_expr) => ExpressionKind::If(Box::new(IfExpression { - condition: remove_interned_in_expression(interner, if_expr.condition), - consequence: remove_interned_in_expression(interner, if_expr.consequence), - alternative: if_expr - .alternative - .map(|alternative| remove_interned_in_expression(interner, alternative)), - })), - ExpressionKind::Variable(_) => expr, - ExpressionKind::Tuple(expressions) => ExpressionKind::Tuple(vecmap(expressions, |expr| { - remove_interned_in_expression(interner, expr) - })), - ExpressionKind::Lambda(lambda) => ExpressionKind::Lambda(Box::new(Lambda { - body: remove_interned_in_expression(interner, lambda.body), - ..*lambda - })), - ExpressionKind::Parenthesized(expr) => { - ExpressionKind::Parenthesized(Box::new(remove_interned_in_expression(interner, *expr))) - } - ExpressionKind::Quote(_) => expr, - ExpressionKind::Unquote(expr) => { - ExpressionKind::Unquote(Box::new(remove_interned_in_expression(interner, *expr))) - } - ExpressionKind::Comptime(block, span) => { - let statements = - vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); - ExpressionKind::Comptime(BlockExpression { statements }, span) - } - ExpressionKind::Unsafe(block, span) => { - let statements = - vecmap(block.statements, |stmt| remove_interned_in_statement(interner, stmt)); - ExpressionKind::Unsafe(BlockExpression { statements }, span) - } - ExpressionKind::AsTraitPath(mut path) => { - path.typ = remove_interned_in_unresolved_type(interner, path.typ); - path.trait_generics = - remove_interned_in_generic_type_args(interner, path.trait_generics); - ExpressionKind::AsTraitPath(path) - } - ExpressionKind::TypePath(mut path) => { - path.typ = remove_interned_in_unresolved_type(interner, path.typ); - path.turbofish = remove_interned_in_generic_type_args(interner, path.turbofish); - ExpressionKind::TypePath(path) - } - ExpressionKind::Resolved(id) => { - let expr = interner.expression(&id); - expr.to_display_ast(interner, Span::default()).kind - } - ExpressionKind::Interned(id) => { - let expr = interner.get_expression_kind(id).clone(); - remove_interned_in_expression_kind(interner, expr) - } - ExpressionKind::Error => expr, - ExpressionKind::InternedStatement(id) => remove_interned_in_statement_expr(interner, id), - } -} - -fn remove_interned_in_statement_expr( - interner: &NodeInterner, - id: InternedStatementKind, -) -> ExpressionKind { - let expr = match interner.get_statement_kind(id).clone() { - StatementKind::Expression(expr) | StatementKind::Semi(expr) => expr.kind, - StatementKind::Interned(id) => remove_interned_in_statement_expr(interner, id), - _ => ExpressionKind::Error, - }; - remove_interned_in_expression_kind(interner, expr) -} - -fn remove_interned_in_literal(interner: &NodeInterner, literal: Literal) -> Literal { - match literal { - Literal::Array(array_literal) => { - Literal::Array(remove_interned_in_array_literal(interner, array_literal)) - } - Literal::Slice(array_literal) => { - Literal::Array(remove_interned_in_array_literal(interner, array_literal)) - } - Literal::Bool(_) - | Literal::Integer(_, _) - | Literal::Str(_) - | Literal::RawStr(_, _) - | Literal::FmtStr(_) - | Literal::Unit => literal, - } -} - -fn remove_interned_in_array_literal( - interner: &NodeInterner, - literal: ArrayLiteral, -) -> ArrayLiteral { - match literal { - ArrayLiteral::Standard(expressions) => { - ArrayLiteral::Standard(vecmap(expressions, |expr| { - remove_interned_in_expression(interner, expr) - })) - } - ArrayLiteral::Repeated { repeated_element, length } => ArrayLiteral::Repeated { - repeated_element: Box::new(remove_interned_in_expression(interner, *repeated_element)), - length: Box::new(remove_interned_in_expression(interner, *length)), - }, - } -} - -// Returns a new Statement where all Interned statements have been turned into non-interned StatementKind. -fn remove_interned_in_statement(interner: &NodeInterner, statement: Statement) -> Statement { - Statement { - kind: remove_interned_in_statement_kind(interner, statement.kind), - span: statement.span, - } -} - -// Returns a new StatementKind where all Interned statements have been turned into non-interned StatementKind. -fn remove_interned_in_statement_kind( - interner: &NodeInterner, - statement: StatementKind, -) -> StatementKind { - match statement { - StatementKind::Let(let_statement) => StatementKind::Let(LetStatement { - pattern: remove_interned_in_pattern(interner, let_statement.pattern), - expression: remove_interned_in_expression(interner, let_statement.expression), - r#type: remove_interned_in_unresolved_type(interner, let_statement.r#type), - ..let_statement - }), - StatementKind::Constrain(constrain) => StatementKind::Constrain(ConstrainStatement( - remove_interned_in_expression(interner, constrain.0), - constrain.1.map(|expr| remove_interned_in_expression(interner, expr)), - constrain.2, - )), - StatementKind::Expression(expr) => { - StatementKind::Expression(remove_interned_in_expression(interner, expr)) - } - StatementKind::Assign(assign) => StatementKind::Assign(AssignStatement { - lvalue: assign.lvalue, - expression: remove_interned_in_expression(interner, assign.expression), - }), - StatementKind::For(for_loop) => StatementKind::For(ForLoopStatement { - range: match for_loop.range { - ForRange::Range(from, to) => ForRange::Range( - remove_interned_in_expression(interner, from), - remove_interned_in_expression(interner, to), - ), - ForRange::Array(expr) => { - ForRange::Array(remove_interned_in_expression(interner, expr)) - } - }, - block: remove_interned_in_expression(interner, for_loop.block), - ..for_loop - }), - StatementKind::Comptime(statement) => { - StatementKind::Comptime(Box::new(remove_interned_in_statement(interner, *statement))) - } - StatementKind::Semi(expr) => { - StatementKind::Semi(remove_interned_in_expression(interner, expr)) - } - StatementKind::Interned(id) => { - let statement = interner.get_statement_kind(id).clone(); - remove_interned_in_statement_kind(interner, statement) - } - StatementKind::Break | StatementKind::Continue | StatementKind::Error => statement, - } -} - -// Returns a new LValue where all Interned LValues have been turned into LValue. -fn remove_interned_in_lvalue(interner: &NodeInterner, lvalue: LValue) -> LValue { - match lvalue { - LValue::Ident(_) => lvalue, - LValue::MemberAccess { object, field_name, span } => LValue::MemberAccess { - object: Box::new(remove_interned_in_lvalue(interner, *object)), - field_name, - span, - }, - LValue::Index { array, index, span } => LValue::Index { - array: Box::new(remove_interned_in_lvalue(interner, *array)), - index: remove_interned_in_expression(interner, index), - span, - }, - LValue::Dereference(lvalue, span) => { - LValue::Dereference(Box::new(remove_interned_in_lvalue(interner, *lvalue)), span) - } - LValue::Interned(id, span) => { - let lvalue = interner.get_lvalue(id, span); - remove_interned_in_lvalue(interner, lvalue) - } - } -} - -fn remove_interned_in_unresolved_type( - interner: &NodeInterner, - typ: UnresolvedType, -) -> UnresolvedType { - UnresolvedType { - typ: remove_interned_in_unresolved_type_data(interner, typ.typ), - span: typ.span, - } -} - -fn remove_interned_in_unresolved_type_data( - interner: &NodeInterner, - typ: UnresolvedTypeData, -) -> UnresolvedTypeData { - match typ { - UnresolvedTypeData::Array(expr, typ) => UnresolvedTypeData::Array( - expr, - Box::new(remove_interned_in_unresolved_type(interner, *typ)), - ), - UnresolvedTypeData::Slice(typ) => { - UnresolvedTypeData::Slice(Box::new(remove_interned_in_unresolved_type(interner, *typ))) - } - UnresolvedTypeData::FormatString(expr, typ) => UnresolvedTypeData::FormatString( - expr, - Box::new(remove_interned_in_unresolved_type(interner, *typ)), - ), - UnresolvedTypeData::Parenthesized(typ) => UnresolvedTypeData::Parenthesized(Box::new( - remove_interned_in_unresolved_type(interner, *typ), - )), - UnresolvedTypeData::Named(path, generic_type_args, is_synthesized) => { - UnresolvedTypeData::Named( - path, - remove_interned_in_generic_type_args(interner, generic_type_args), - is_synthesized, - ) - } - UnresolvedTypeData::TraitAsType(path, generic_type_args) => { - UnresolvedTypeData::TraitAsType( - path, - remove_interned_in_generic_type_args(interner, generic_type_args), - ) - } - UnresolvedTypeData::MutableReference(typ) => UnresolvedTypeData::MutableReference( - Box::new(remove_interned_in_unresolved_type(interner, *typ)), - ), - UnresolvedTypeData::Tuple(types) => UnresolvedTypeData::Tuple(vecmap(types, |typ| { - remove_interned_in_unresolved_type(interner, typ) - })), - UnresolvedTypeData::Function(arg_types, ret_type, env_type, unconstrained) => { - UnresolvedTypeData::Function( - vecmap(arg_types, |typ| remove_interned_in_unresolved_type(interner, typ)), - Box::new(remove_interned_in_unresolved_type(interner, *ret_type)), - Box::new(remove_interned_in_unresolved_type(interner, *env_type)), - unconstrained, - ) - } - UnresolvedTypeData::AsTraitPath(as_trait_path) => { - UnresolvedTypeData::AsTraitPath(Box::new(AsTraitPath { - typ: remove_interned_in_unresolved_type(interner, as_trait_path.typ), - trait_generics: remove_interned_in_generic_type_args( - interner, - as_trait_path.trait_generics, - ), - ..*as_trait_path - })) - } - UnresolvedTypeData::Interned(id) => interner.get_unresolved_type_data(id).clone(), - UnresolvedTypeData::FieldElement - | UnresolvedTypeData::Integer(_, _) - | UnresolvedTypeData::Bool - | UnresolvedTypeData::Unit - | UnresolvedTypeData::String(_) - | UnresolvedTypeData::Resolved(_) - | UnresolvedTypeData::Quoted(_) - | UnresolvedTypeData::Expression(_) - | UnresolvedTypeData::Unspecified - | UnresolvedTypeData::Error => typ, - } -} - -fn remove_interned_in_generic_type_args( - interner: &NodeInterner, - args: GenericTypeArgs, -) -> GenericTypeArgs { - GenericTypeArgs { - ordered_args: vecmap(args.ordered_args, |typ| { - remove_interned_in_unresolved_type(interner, typ) - }), - named_args: vecmap(args.named_args, |(name, typ)| { - (name, remove_interned_in_unresolved_type(interner, typ)) - }), - } -} - -// Returns a new Pattern where all Interned Patterns have been turned into Pattern. -fn remove_interned_in_pattern(interner: &NodeInterner, pattern: Pattern) -> Pattern { - match pattern { - Pattern::Identifier(_) => pattern, - Pattern::Mutable(pattern, span, is_synthesized) => Pattern::Mutable( - Box::new(remove_interned_in_pattern(interner, *pattern)), - span, - is_synthesized, - ), - Pattern::Tuple(patterns, span) => Pattern::Tuple( - vecmap(patterns, |pattern| remove_interned_in_pattern(interner, pattern)), - span, - ), - Pattern::Struct(path, patterns, span) => { - let patterns = vecmap(patterns, |(name, pattern)| { - (name, remove_interned_in_pattern(interner, pattern)) - }); - Pattern::Struct(path, patterns, span) - } - Pattern::Interned(id, _) => interner.get_pattern(id).clone(), - } -} diff --git a/noir/noir-repo/compiler/noirc_frontend/src/hir/type_check/errors.rs b/noir/noir-repo/compiler/noirc_frontend/src/hir/type_check/errors.rs index 155564536d6..00e73e682e8 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/hir/type_check/errors.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/hir/type_check/errors.rs @@ -5,6 +5,7 @@ use noirc_errors::CustomDiagnostic as Diagnostic; use noirc_errors::Span; use thiserror::Error; +use crate::ast::ConstrainKind; use crate::ast::{BinaryOpKind, FunctionReturnType, IntegerBitSize, Signedness}; use crate::hir::resolution::errors::ResolverError; use crate::hir_def::expr::HirBinaryOp; @@ -59,6 +60,8 @@ pub enum TypeCheckError { AccessUnknownMember { lhs_type: Type, field_name: String, span: Span }, #[error("Function expects {expected} parameters but {found} were given")] ParameterCountMismatch { expected: usize, found: usize, span: Span }, + #[error("{} expects {} or {} parameters but {found} were given", kind, kind.required_arguments_count(), kind.required_arguments_count() + 1)] + AssertionParameterCountMismatch { kind: ConstrainKind, found: usize, span: Span }, #[error("{item} expects {expected} generics but {found} were given")] GenericCountMismatch { item: String, expected: usize, found: usize, span: Span }, #[error("{item} has incompatible `unconstrained`")] @@ -260,6 +263,13 @@ impl<'a> From<&'a TypeCheckError> for Diagnostic { let msg = format!("Function expects {expected} parameter{empty_or_s} but {found} {was_or_were} given"); Diagnostic::simple_error(msg, String::new(), *span) } + TypeCheckError::AssertionParameterCountMismatch { kind, found, span } => { + let was_or_were = if *found == 1 { "was" } else { "were" }; + let min = kind.required_arguments_count(); + let max = min + 1; + let msg = format!("{kind} expects {min} or {max} parameters but {found} {was_or_were} given"); + Diagnostic::simple_error(msg, String::new(), *span) + } TypeCheckError::GenericCountMismatch { item, expected, found, span } => { let empty_or_s = if *expected == 1 { "" } else { "s" }; let was_or_were = if *found == 1 { "was" } else { "were" }; diff --git a/noir/noir-repo/compiler/noirc_frontend/src/node_interner.rs b/noir/noir-repo/compiler/noirc_frontend/src/node_interner.rs index d3e5e270b3c..8c00fcde2ef 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/node_interner.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/node_interner.rs @@ -361,7 +361,16 @@ pub enum ImplSearchErrorKind { #[derive(Default, Debug, Clone)] pub struct Methods { pub direct: Vec, - pub trait_impl_methods: Vec, + pub trait_impl_methods: Vec, +} + +#[derive(Debug, Clone)] +pub struct TraitImplMethod { + // This type is only stored for primitive types to be able to + // select the correct static methods between multiple options keyed + // under TypeMethodKey::FieldOrInt + pub typ: Option, + pub method: FuncId, } /// All the information from a function that is filled out during definition collection rather than @@ -1383,7 +1392,7 @@ impl NodeInterner { .or_default() .entry(method_name) .or_default() - .add_method(method_id, is_trait_method); + .add_method(method_id, None, is_trait_method); None } Type::Error => None, @@ -1395,12 +1404,16 @@ impl NodeInterner { let key = get_type_method_key(self_type).unwrap_or_else(|| { unreachable!("Cannot add a method to the unsupported type '{}'", other) }); + // Only remember the actual type if it's FieldOrInt, + // so later we can disambiguate on calls like `u32::call`. + let typ = + if key == TypeMethodKey::FieldOrInt { Some(self_type.clone()) } else { None }; self.primitive_methods .entry(key) .or_default() .entry(method_name) .or_default() - .add_method(method_id, is_trait_method); + .add_method(method_id, typ, is_trait_method); None } } @@ -2246,23 +2259,29 @@ impl Methods { if self.direct.len() == 1 { Some(self.direct[0]) } else if self.direct.is_empty() && self.trait_impl_methods.len() == 1 { - Some(self.trait_impl_methods[0]) + Some(self.trait_impl_methods[0].method) } else { None } } - fn add_method(&mut self, method: FuncId, is_trait_method: bool) { + fn add_method(&mut self, method: FuncId, typ: Option, is_trait_method: bool) { if is_trait_method { - self.trait_impl_methods.push(method); + let trait_impl_method = TraitImplMethod { typ, method }; + self.trait_impl_methods.push(trait_impl_method); } else { self.direct.push(method); } } /// Iterate through each method, starting with the direct methods - pub fn iter(&self) -> impl Iterator + '_ { - self.direct.iter().copied().chain(self.trait_impl_methods.iter().copied()) + pub fn iter(&self) -> impl Iterator)> + '_ { + let trait_impl_methods = self.trait_impl_methods.iter().map(|m| (m.method, &m.typ)); + let direct = self.direct.iter().copied().map(|func_id| { + let typ: &Option = &None; + (func_id, typ) + }); + direct.chain(trait_impl_methods) } /// Select the 1 matching method with an object type matching `typ` @@ -2274,28 +2293,32 @@ impl Methods { ) -> Option { // When adding methods we always check they do not overlap, so there should be // at most 1 matching method in this list. - for method in self.iter() { + for (method, method_type) in self.iter() { match interner.function_meta(&method).typ.instantiate(interner).0 { Type::Function(args, _, _, _) => { if has_self_param { if let Some(object) = args.first() { - let mut bindings = TypeBindings::new(); - - if object.try_unify(typ, &mut bindings).is_ok() { - Type::apply_type_bindings(bindings); + if object.unify(typ).is_ok() { return Some(method); } } } else { - // Just return the first method whose name matches since we - // can't match object types on static methods. - return Some(method); + // If we recorded the concrete type this trait impl method belongs to, + // and it matches typ, it's an exact match and we return that. + if let Some(method_type) = method_type { + if method_type.unify(typ).is_ok() { + return Some(method); + } + } else { + return Some(method); + } } } Type::Error => (), other => unreachable!("Expected function type, found {other}"), } } + None } } diff --git a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser.rs b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser.rs index 337563213e5..b007653062b 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser.rs @@ -465,7 +465,6 @@ where choice(( assertion::constrain(expr_parser.clone()), assertion::assertion(expr_parser.clone()), - assertion::assertion_eq(expr_parser.clone()), declaration(expr_parser.clone()), assignment(expr_parser.clone()), if_statement(expr_no_constructors.clone(), statement.clone()), @@ -1629,17 +1628,13 @@ mod test { Case { source: "let", expect: "let $error = Error", errors: 3 }, Case { source: "foo = one two three", expect: "foo = one", errors: 1 }, Case { source: "constrain", expect: "constrain Error", errors: 2 }, - Case { source: "assert", expect: "constrain Error", errors: 1 }, + Case { source: "assert", expect: "assert()", errors: 1 }, Case { source: "constrain x ==", expect: "constrain (x == Error)", errors: 2 }, - Case { source: "assert(x ==)", expect: "constrain (x == Error)", errors: 1 }, - Case { source: "assert(x == x, x)", expect: "constrain (x == x)", errors: 0 }, - Case { source: "assert_eq(x,)", expect: "constrain (Error == Error)", errors: 1 }, - Case { - source: "assert_eq(x, x, x, x)", - expect: "constrain (Error == Error)", - errors: 1, - }, - Case { source: "assert_eq(x, x, x)", expect: "constrain (x == x)", errors: 0 }, + Case { source: "assert(x ==)", expect: "assert((x == Error))", errors: 1 }, + Case { source: "assert(x == x, x)", expect: "assert((x == x), x)", errors: 0 }, + Case { source: "assert_eq(x,)", expect: "assert_eq(x)", errors: 0 }, + Case { source: "assert_eq(x, x, x, x)", expect: "assert_eq(x, x, x, x)", errors: 0 }, + Case { source: "assert_eq(x, x, x)", expect: "assert_eq(x, x, x)", errors: 0 }, ]; check_cases_with_errors(&cases[..], fresh_statement()); diff --git a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/assertion.rs b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/assertion.rs index ed08a4c9922..9eb429ef295 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/assertion.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/assertion.rs @@ -1,14 +1,11 @@ -use crate::ast::{Expression, ExpressionKind, StatementKind}; -use crate::parser::{ - ignore_then_commit, labels::ParsingRuleLabel, parenthesized, ExprParser, NoirParser, - ParserError, ParserErrorReason, -}; +use crate::ast::StatementKind; +use crate::parser::{ignore_then_commit, then_commit, ParserError, ParserErrorReason}; +use crate::parser::{labels::ParsingRuleLabel, parenthesized, ExprParser, NoirParser}; -use crate::ast::{BinaryOpKind, ConstrainKind, ConstrainStatement, InfixExpression, Recoverable}; +use crate::ast::{ConstrainKind, ConstrainStatement}; use crate::token::{Keyword, Token}; use chumsky::prelude::*; -use noirc_errors::Spanned; use super::keyword; @@ -20,7 +17,13 @@ where keyword(Keyword::Constrain).labelled(ParsingRuleLabel::Statement), expr_parser, ) - .map(|expr| StatementKind::Constrain(ConstrainStatement(expr, None, ConstrainKind::Constrain))) + .map_with_span(|expr, span| { + StatementKind::Constrain(ConstrainStatement { + kind: ConstrainKind::Constrain, + arguments: vec![expr], + span, + }) + }) .validate(|expr, span, emit| { emit(ParserError::with_reason(ParserErrorReason::ConstrainDeprecated, span)); expr @@ -31,42 +34,17 @@ pub(super) fn assertion<'a, P>(expr_parser: P) -> impl NoirParser where P: ExprParser + 'a, { - let argument_parser = - expr_parser.separated_by(just(Token::Comma)).allow_trailing().at_least(1).at_most(2); - - ignore_then_commit(keyword(Keyword::Assert), parenthesized(argument_parser)) - .labelled(ParsingRuleLabel::Statement) - .validate(|expressions, span, _| { - let condition = expressions.first().unwrap_or(&Expression::error(span)).clone(); - let message = expressions.get(1).cloned(); - StatementKind::Constrain(ConstrainStatement(condition, message, ConstrainKind::Assert)) - }) -} + let keyword = choice(( + keyword(Keyword::Assert).map(|_| ConstrainKind::Assert), + keyword(Keyword::AssertEq).map(|_| ConstrainKind::AssertEq), + )); -pub(super) fn assertion_eq<'a, P>(expr_parser: P) -> impl NoirParser + 'a -where - P: ExprParser + 'a, -{ - let argument_parser = - expr_parser.separated_by(just(Token::Comma)).allow_trailing().at_least(2).at_most(3); + let argument_parser = expr_parser.separated_by(just(Token::Comma)).allow_trailing(); - ignore_then_commit(keyword(Keyword::AssertEq), parenthesized(argument_parser)) + then_commit(keyword, parenthesized(argument_parser)) .labelled(ParsingRuleLabel::Statement) - .validate(|exprs: Vec, span, _| { - let predicate = Expression::new( - ExpressionKind::Infix(Box::new(InfixExpression { - lhs: exprs.first().unwrap_or(&Expression::error(span)).clone(), - rhs: exprs.get(1).unwrap_or(&Expression::error(span)).clone(), - operator: Spanned::from(span, BinaryOpKind::Equal), - })), - span, - ); - let message = exprs.get(2).cloned(); - StatementKind::Constrain(ConstrainStatement( - predicate, - message, - ConstrainKind::AssertEq, - )) + .map_with_span(|(kind, arguments), span| { + StatementKind::Constrain(ConstrainStatement { arguments, kind, span }) }) } @@ -74,7 +52,7 @@ where mod test { use super::*; use crate::{ - ast::Literal, + ast::{BinaryOpKind, ExpressionKind, Literal}, parser::parser::{ expression, test_helpers::{parse_all, parse_all_failing, parse_with}, @@ -174,11 +152,11 @@ mod test { match parse_with(assertion(expression()), "assert(x == y, \"assertion message\")").unwrap() { - StatementKind::Constrain(ConstrainStatement(_, message, _)) => { - let message = message.unwrap(); - match message.kind { + StatementKind::Constrain(ConstrainStatement { arguments, .. }) => { + let message = arguments.last().unwrap(); + match &message.kind { ExpressionKind::Literal(Literal::Str(message_string)) => { - assert_eq!(message_string, "assertion message".to_owned()); + assert_eq!(message_string, "assertion message"); } _ => unreachable!(), } @@ -191,7 +169,7 @@ mod test { #[test] fn parse_assert_eq() { parse_all( - assertion_eq(expression()), + assertion(expression()), vec![ "assert_eq(x, y)", "assert_eq(((x + y) == k) + z, y)", @@ -201,14 +179,13 @@ mod test { "assert_eq(x + x ^ x, y | m)", ], ); - match parse_with(assertion_eq(expression()), "assert_eq(x, y, \"assertion message\")") - .unwrap() + match parse_with(assertion(expression()), "assert_eq(x, y, \"assertion message\")").unwrap() { - StatementKind::Constrain(ConstrainStatement(_, message, _)) => { - let message = message.unwrap(); - match message.kind { + StatementKind::Constrain(ConstrainStatement { arguments, .. }) => { + let message = arguments.last().unwrap(); + match &message.kind { ExpressionKind::Literal(Literal::Str(message_string)) => { - assert_eq!(message_string, "assertion message".to_owned()); + assert_eq!(message_string, "assertion message"); } _ => unreachable!(), } diff --git a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/path.rs b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/path.rs index 3e964d271a0..1c9c24f5376 100644 --- a/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/path.rs +++ b/noir/noir-repo/compiler/noirc_frontend/src/parser/parser/path.rs @@ -1,10 +1,11 @@ -use crate::ast::{AsTraitPath, Path, PathKind, PathSegment, TypePath, UnresolvedType}; +use crate::ast::{AsTraitPath, Ident, Path, PathKind, PathSegment, TypePath, UnresolvedType}; use crate::macros_api::ExpressionKind; use crate::parser::{NoirParser, ParserError, ParserErrorReason}; use crate::token::{Keyword, Token}; use chumsky::prelude::*; +use noirc_errors::Span; use super::keyword; use super::primitives::{ident, path_segment, path_segment_no_turbofish, turbofish}; @@ -78,10 +79,19 @@ pub(super) fn type_path<'a>( ) -> impl NoirParser + 'a { primitive_type() .then_ignore(just(Token::DoubleColon)) - .then(ident()) + .then(ident().or_not()) .then(turbofish(type_parser)) - .map(|((typ, item), turbofish)| { + .validate(|((typ, item), turbofish), span, emit| { let turbofish = turbofish.unwrap_or_default(); + let item = if let Some(item) = item { + item + } else { + emit(ParserError::with_reason( + ParserErrorReason::ExpectedIdentifierAfterColons, + span, + )); + Ident::new(String::new(), Span::from(span.end()..span.end())) + }; ExpressionKind::TypePath(TypePath { typ, item, turbofish }) }) } diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/examples/merkle-proof.mdx deleted file mode 100644 index 6430780817c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/00_nargo_installation.md deleted file mode 100644 index 0de5597c213..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `flake.nix`, which is 1.66.0 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -Windows is not directly supported at this time. To install Noir on a Windows machine, it is recommended to use WSL. - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/01_hello_world.md deleted file mode 100644 index 34f8cd96fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/02_breakdown.md deleted file mode 100644 index 8616feee917..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` (optional) - specifies the version of the compiler to use. This is not currently enforced by the compiler, but will be in future versions. -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/index.md deleted file mode 100644 index c88aabf0ac1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/index.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands.md#nargo-codegen-verifier) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/06_generics.md deleted file mode 100644 index 36c2b593fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/06_generics.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/01_integers.md deleted file mode 100644 index d9c5e20e795..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Integers -description: - Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: - [ - noir, - integer types, - methods, - examples, - arithmetic, - ] ---- - -An integer type is a range constrained field type. The Noir frontend currently supports unsigned, -arbitrary-sized integer types. - -An integer type is specified first with the letter `u`, indicating its unsigned nature, followed by -its length in bits (e.g. `32`). For example, a `u32` variable can store a value in the range of -$\\([0,2^{32}-1]\\)$: - -```rust -fn main(x : Field, y : u32) { - let z = x as u32 + y; -} -``` - -`x`, `y` and `z` are all private values in this example. However, `x` is a field while `y` and `z` -are unsigned 32-bit integers. If `y` or `z` exceeds the range $\\([0,2^{32}-1]\\)$, proofs created -will be rejected by the verifier. - -> **Note:** The default backend supports both even (e.g. `u16`, `u48`) and odd (e.g. `u5`, `u3`) -> sized integer types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/02_booleans.md deleted file mode 100644 index d353606210a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/03_strings.md deleted file mode 100644 index 4360893e9a2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 3c84da3f8ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index f45f56daee1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here]([test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/08_structs.md deleted file mode 100644 index 85649dfb389..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. - -:::note -You can use Structs as inputs to the `main` function, but you can't output them -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/migration_notes.md deleted file mode 100644 index 1a81af04b3a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/migration_notes.md +++ /dev/null @@ -1,83 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/dependencies.md deleted file mode 100644 index 87a09293ea8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/01_commands.md deleted file mode 100644 index e2b0af522f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index b3f1d6df747..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,256 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/noir_js.md deleted file mode 100644 index 23ea550e156..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/01_noirjs.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/01_noirjs.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/01_noirjs.md deleted file mode 100644 index 3480fbfedad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/01_noirjs.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: Noir -description: Reference to noir_js library and the Noir class -keywords: [Noir project, javascript, typescript, node.js, browser, react, class, reference] ---- - -## Table of Contents - -- [constructor](#constructor) -- [init](#init) -- [generateFinalProof](#generatefinalproof) -- [verifyFinalProof](#verifyfinalproof) - -## `constructor` - -The `constructor` is a method used to create and initialize objects created within the `Noir` class. In the `Noir` class constructor, you need to pass two parameters: `circuit` and `backend`. - -### Syntax - -```js -constructor(circuit, backend); -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `circuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode. Typically obtained by running [`nargo compile`](../../nargo/01_commands.md) | -| `backend` | Object | A backend instance, before initialization. | - -### Usage - -```js -const noir = new Noir(circuit, backend); -``` - -## `init` - -This async method should be called after class instantiation. It will run processes on the ACVM, instantiate your backend, etc. - -### Syntax - -```js -async init() -``` - -### Parameters - -This method takes no parameters - -### Usage - -```js -await noirInstance.init(); -``` - -## `execute` - -This async method allows to execute a circuit to get its witness and return value. [`generateFinalProof`](#generatefinalproof) calls it for you, but you can call it directly (i.e. to feed directly to a backend, or to get the return value). - -### Syntax - -```js -async execute(inputs) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------ | -| `inputs` | Object | An object containing the inputs to your circuit. | - -### Returns - -| Return value | Type | Description | -| ------------ | --------------------- | --------------------------------------------------- | -| `witness` | Promise \ | The witness | -| `returnValue` | Promise \ | The return value | - -### Usage - -```js -const { witness, returnValue } = await noir.execute(inputs) -``` - -## `generateFinalProof` - -This async method generates a witness and a proof given an object as input. - -### Syntax - -```js -async generateFinalProof(input) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------ | -| `input` | Object | An object containing the inputs to your circuit. | - -### Returns - -| Return value | Type | Description | -| ------------ | --------------------- | --------------------------------------------------- | -| `proof` | Promise \ | An array with the byte representation of the proof. | - -### Usage - -```js -// consider the Standard Noir Example given with nargo init -const input = { x: 1, y: 2 }; -noirInstance.generateProof(input); -``` - -## `verifyFinalProof` - -This async method instantiates the verification key and verifies your proof. - -### Syntax - -```js -async verifyFinalProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ---------- | --------------------------------------------------------------------------------------------- | -| `proof` | Uint8Array | The Uint8Array representation of your proof, usually obtained by calling `generateFinalProof` | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const proof = noirInstance.generateProof(input); -noirInstance.verifyFinalProof(proof); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/02_bb_backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/02_bb_backend.md deleted file mode 100644 index 958cabd6289..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/noir_js/reference/02_bb_backend.md +++ /dev/null @@ -1,272 +0,0 @@ ---- -title: BarretenbergBackend -description: Reference documentation for the barretenberg_backend library and the BarretenbergBackend class -keywords: - [ - BarretenbergBackend, - Barretenberg, - javascript, - typescript, - node.js, - browser, - class, - reference, - noir_js, - ] ---- - -## Table of Contents - -- [constructor](#constructor) -- [generateFinalProof](#generatefinalproof) -- [generateIntermediateProof](#generateintermediateproof) -- [generateProof](#generateproof) -- [generateIntermediateProofArtifacts](#generateintermediateproofartifacts) -- [verifyFinalProof](#verifyfinalproof) -- [verifyIntermediateProof](#verifyintermediateproof) -- [verifyProof](#verifyproof) -- [destroy](#destroy) - -## `constructor` - -The `constructor` is a method used to create and initialize objects created within the `BarretenbergBackend` class. In this class, you should pass at least one argument for the `circuit`. - -### Syntax - -```js -constructor(acirCircuit, (numberOfThreads = 1)); -``` - -### Parameters - -| Parameter | Type | Description | -| ----------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `acirCircuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode typically obtained by running [`nargo compile`](../../nargo/01_commands.md). This is the same circuit expected to be passed to [the Noir class](01_noirjs.md) | -| `numberOfThreads` | Number (optional) | The number of threads to be used by the backend. Defaults to 1. | - -### Usage - -```js -const backend = new BarretenbergBackend(acirCircuit); -``` - -## `generateFinalProof` - -An async wrapper around the [generateProof](#generateproof) method that passes a `false` flag. Usually called by the Noir class. - -### Syntax - -```js -async generateFinalProof(decompressedWitness) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------- | ------ | -------------------------------------------------------- | -| `decompressedWitness` | Object | The decompressed witness for generating the final proof. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | --------------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the final proof. | - -### Usage - -```js -const finalProof = await backend.generateFinalProof(decompressedWitness); -``` - -## `generateIntermediateProof` - -An async wrapper around the [generateProof](#generateproof) method that passes a `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async generateIntermediateProof(witness) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | -------------------------------------------------- | -| `witness` | Object | The witness for generating the intermediate proof. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | --------------------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the intermediate proof | - -### Usage - -```js -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -## `generateProof` - -This async method generates a proof. Takes the witness generated by ACVM, and a boolean that evaluates to `true` when the proof _is_ meant to be verified in another circuit. Not currently used by the Noir class. - -### Syntax - -```js -async generateProof(decompressedWitness, makeEasyToVerifyInCircuit) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------------- | ------- | ---------------------------------------------------------------------------------------------- | -| `decompressedWitness` | Object | The decompressed witness for generating the proof. | -| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether to generate proof components for easy verification within a circuit. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | -------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the proof | - -### Usage - -```js -const proof = await backend.generateProof(decompressedWitness, makeEasyToVerifyInCircuit); -``` - -## `generateIntermediateProofArtifacts` - -This async method returns the artifacts needed to verify the intermediate proof in another circuit. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async generateIntermediateProofArtifacts(proof, numOfPublicInputs = 0) -``` - -### Parameters - -| Parameter | Type | Description | -| ------------------- | ----------------- | ---------------------------------------------------------------- | -| `proof` | Object | The proof object. | -| `numOfPublicInputs` | Number (optional) | The number of public inputs in the inner proof, defaulting to 0. | - -### Returns - -| Return value | Type | Description | -| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `proofAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up a proof | -| `vkAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up the verification key | -| `vkHash` | string | A pedersen hash of the verification key | - -### Usage - -```js -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -## `verifyFinalProof` - -An async wrapper around [verifyProof](#verifyproof) that sets the `false` flag. Usually called by the Noir class. - -### Syntax - -```js -async verifyFinalProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | --------------------------- | -| `proof` | Object | The proof object to verify. | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValidFinal = await backend.verifyFinalProof(proof); -``` - -## `verifyIntermediateProof` - -An async wrapper around [verifyProof](#verifyproof) that sets the `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async verifyIntermediateProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ---------------------------------------- | -| `proof` | Object | The intermediate proof object to verify. | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -## `verifyProof` - -This async method verifies a proof. Takes the proof, and a boolean that evaluates to `true` when the proof is intermediate. - -### Syntax - -```js -async verifyProof(proof, makeEasyToVerifyInCircuit) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------------- | ------- | ------------------------------------------------------------ | -| `proof` | Object | The proof object to verify | -| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether the proof is intermediate or final | - -### Returns - -| Parameter | Type | Description | -| ---------- | ------------------ | -------------------------------------------- | -| `verified` | Promise\ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValid = await backend.verifyProof(proof, makeEasyToVerifyInCircuit); -``` - -## `destroy` - -This method destroys the resources allocated in the [instantiate](#instantiate) method. Noir doesn't currently call this method, but it's highly recommended that developers do so in order to save resources. - -### Syntax - -```js -async destroy() -``` - -### Parameters - -This method takes no parameters. - -### Usage - -```js -await backend.destroy(); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/black_box_fns.md deleted file mode 100644 index b4dedefe4c9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/black_box_fns.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen](./cryptographic_primitives/hashes.mdx#pedersen) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 2cc3cd81e4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index 0f431e40056..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.17.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.17.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/merkle_trees.md deleted file mode 100644 index 9761105f4f2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.17.0/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/examples/merkle-proof.mdx deleted file mode 100644 index 832fb4bb55e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/00_nargo_installation.md deleted file mode 100644 index 7d3c88c7693..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/01_hello_world.md deleted file mode 100644 index 34f8cd96fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/02_breakdown.md deleted file mode 100644 index f928370b2e8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/index.md deleted file mode 100644 index e8d86020a20..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier.md) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen Commitment -- Pedersen Hash -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/06_generics.md deleted file mode 100644 index a932d7b47c2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/06_generics.md +++ /dev/null @@ -1,109 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/01_integers.md deleted file mode 100644 index 1814365800a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/02_booleans.md deleted file mode 100644 index d353606210a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/03_strings.md deleted file mode 100644 index 4360893e9a2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 3c84da3f8ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index 1be0ec4a137..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/08_structs.md deleted file mode 100644 index 85649dfb389..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. - -:::note -You can use Structs as inputs to the `main` function, but you can't output them -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/migration_notes.md deleted file mode 100644 index 905bca3d30c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/dependencies.md deleted file mode 100644 index 87a09293ea8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/01_commands.md deleted file mode 100644 index e2b0af522f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index 64ba4a2c44a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/noir_js.md deleted file mode 100644 index 23ea550e156..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/01_noirjs.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/01_noirjs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/01_noirjs.md deleted file mode 100644 index 2e90779ceab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/01_noirjs.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Noir -description: Reference to noir_js library and the Noir class -keywords: [Noir project, javascript, typescript, node.js, browser, react, class, reference] ---- - -## Table of Contents - -- [constructor](#constructor) -- [init](#init) -- [generateFinalProof](#generatefinalproof) -- [verifyFinalProof](#verifyfinalproof) - -## `constructor` - -The `constructor` is a method used to create and initialize objects created within the `Noir` class. In the `Noir` class constructor, you need to pass two parameters: `circuit` and `backend`. - -### Syntax - -```js -constructor(circuit, backend); -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `circuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode. Typically obtained by running [`nargo compile`](../../nargo/01_commands.md) | -| `backend` | Object | A backend instance, before initialization. | - -### Usage - -```js -const noir = new Noir(circuit, backend); -``` - -## `init` - -This async method should be called after class instantiation. It will run processes on the ACVM, instantiate your backend, etc. - -### Syntax - -```js -async init() -``` - -### Parameters - -This method takes no parameters - -### Usage - -```js -await noirInstance.init(); -``` - -## `execute` - -This async method allows to execute a circuit to get its witness and return value. [`generateFinalProof`](#generatefinalproof) calls it for you, but you can call it directly (i.e. to feed directly to a backend, or to get the return value). - -You can optionally provide a foreignCallHandler, to handle functions that should run outside of the prover (e.g. `std::println`) - -### Syntax - -```js -async execute(inputs, foreignCallHandler) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------ | -| `inputs` | Object | An object containing the inputs to your circuit. | -| `foreignCallHandler` (optional) | Function | A function handling the foreign call from your circuit | - -### Returns - -| Return value | Type | Description | -| ------------ | --------------------- | --------------------------------------------------- | -| `witness` | Promise \ | The witness | -| `returnValue` | Promise \ | The return value | - -### Usage - -```js -const { witness, returnValue } = await noir.execute(inputs) -const { witness, returnValue } = await noir.execute(inputs, (name, args) => console.log(`Received foreign call ${name} with arguments ${args}`)) -``` - -## `generateFinalProof` - -This async method generates a witness and a proof given an object as input. - -### Syntax - -```js -async generateFinalProof(input) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ------------------------------------------------ | -| `input` | Object | An object containing the inputs to your circuit. | - -### Returns - -| Return value | Type | Description | -| ------------ | --------------------- | --------------------------------------------------- | -| `proof` | Promise \ | An array with the byte representation of the proof. | - -### Usage - -```js -// consider the Standard Noir Example given with nargo init -const input = { x: 1, y: 2 }; -noirInstance.generateProof(input); -``` - -## `verifyFinalProof` - -This async method instantiates the verification key and verifies your proof. - -### Syntax - -```js -async verifyFinalProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ---------- | --------------------------------------------------------------------------------------------- | -| `proof` | Uint8Array | The Uint8Array representation of your proof, usually obtained by calling `generateFinalProof` | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const proof = noirInstance.generateProof(input); -noirInstance.verifyFinalProof(proof); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/02_bb_backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/02_bb_backend.md deleted file mode 100644 index 958cabd6289..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/02_bb_backend.md +++ /dev/null @@ -1,272 +0,0 @@ ---- -title: BarretenbergBackend -description: Reference documentation for the barretenberg_backend library and the BarretenbergBackend class -keywords: - [ - BarretenbergBackend, - Barretenberg, - javascript, - typescript, - node.js, - browser, - class, - reference, - noir_js, - ] ---- - -## Table of Contents - -- [constructor](#constructor) -- [generateFinalProof](#generatefinalproof) -- [generateIntermediateProof](#generateintermediateproof) -- [generateProof](#generateproof) -- [generateIntermediateProofArtifacts](#generateintermediateproofartifacts) -- [verifyFinalProof](#verifyfinalproof) -- [verifyIntermediateProof](#verifyintermediateproof) -- [verifyProof](#verifyproof) -- [destroy](#destroy) - -## `constructor` - -The `constructor` is a method used to create and initialize objects created within the `BarretenbergBackend` class. In this class, you should pass at least one argument for the `circuit`. - -### Syntax - -```js -constructor(acirCircuit, (numberOfThreads = 1)); -``` - -### Parameters - -| Parameter | Type | Description | -| ----------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `acirCircuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode typically obtained by running [`nargo compile`](../../nargo/01_commands.md). This is the same circuit expected to be passed to [the Noir class](01_noirjs.md) | -| `numberOfThreads` | Number (optional) | The number of threads to be used by the backend. Defaults to 1. | - -### Usage - -```js -const backend = new BarretenbergBackend(acirCircuit); -``` - -## `generateFinalProof` - -An async wrapper around the [generateProof](#generateproof) method that passes a `false` flag. Usually called by the Noir class. - -### Syntax - -```js -async generateFinalProof(decompressedWitness) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------- | ------ | -------------------------------------------------------- | -| `decompressedWitness` | Object | The decompressed witness for generating the final proof. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | --------------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the final proof. | - -### Usage - -```js -const finalProof = await backend.generateFinalProof(decompressedWitness); -``` - -## `generateIntermediateProof` - -An async wrapper around the [generateProof](#generateproof) method that passes a `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async generateIntermediateProof(witness) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | -------------------------------------------------- | -| `witness` | Object | The witness for generating the intermediate proof. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | --------------------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the intermediate proof | - -### Usage - -```js -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -## `generateProof` - -This async method generates a proof. Takes the witness generated by ACVM, and a boolean that evaluates to `true` when the proof _is_ meant to be verified in another circuit. Not currently used by the Noir class. - -### Syntax - -```js -async generateProof(decompressedWitness, makeEasyToVerifyInCircuit) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------------- | ------- | ---------------------------------------------------------------------------------------------- | -| `decompressedWitness` | Object | The decompressed witness for generating the proof. | -| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether to generate proof components for easy verification within a circuit. | - -### Returns - -| Return value | Type | Description | -| ------------ | -------------------- | -------------------------------------------------- | -| `proof` | Promise\ | An array with the byte representation of the proof | - -### Usage - -```js -const proof = await backend.generateProof(decompressedWitness, makeEasyToVerifyInCircuit); -``` - -## `generateIntermediateProofArtifacts` - -This async method returns the artifacts needed to verify the intermediate proof in another circuit. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async generateIntermediateProofArtifacts(proof, numOfPublicInputs = 0) -``` - -### Parameters - -| Parameter | Type | Description | -| ------------------- | ----------------- | ---------------------------------------------------------------- | -| `proof` | Object | The proof object. | -| `numOfPublicInputs` | Number (optional) | The number of public inputs in the inner proof, defaulting to 0. | - -### Returns - -| Return value | Type | Description | -| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `proofAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up a proof | -| `vkAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up the verification key | -| `vkHash` | string | A pedersen hash of the verification key | - -### Usage - -```js -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -## `verifyFinalProof` - -An async wrapper around [verifyProof](#verifyproof) that sets the `false` flag. Usually called by the Noir class. - -### Syntax - -```js -async verifyFinalProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | --------------------------- | -| `proof` | Object | The proof object to verify. | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValidFinal = await backend.verifyFinalProof(proof); -``` - -## `verifyIntermediateProof` - -An async wrapper around [verifyProof](#verifyproof) that sets the `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. - -### Syntax - -```js -async verifyIntermediateProof(proof) -``` - -### Parameters - -| Parameter | Type | Description | -| --------- | ------ | ---------------------------------------- | -| `proof` | Object | The intermediate proof object to verify. | - -### Returns - -| Return value | Type | Description | -| ------------ | ------------------ | -------------------------------------------- | -| `verified` | Promise \ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -## `verifyProof` - -This async method verifies a proof. Takes the proof, and a boolean that evaluates to `true` when the proof is intermediate. - -### Syntax - -```js -async verifyProof(proof, makeEasyToVerifyInCircuit) -``` - -### Parameters - -| Parameter | Type | Description | -| --------------------------- | ------- | ------------------------------------------------------------ | -| `proof` | Object | The proof object to verify | -| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether the proof is intermediate or final | - -### Returns - -| Parameter | Type | Description | -| ---------- | ------------------ | -------------------------------------------- | -| `verified` | Promise\ | A boolean for whether the proof was verified | - -### Usage - -```js -const isValid = await backend.verifyProof(proof, makeEasyToVerifyInCircuit); -``` - -## `destroy` - -This method destroys the resources allocated in the [instantiate](#instantiate) method. Noir doesn't currently call this method, but it's highly recommended that developers do so in order to save resources. - -### Syntax - -```js -async destroy() -``` - -### Parameters - -This method takes no parameters. - -### Usage - -```js -await backend.destroy(); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 3680ba3ca77..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index 1d7b54a9dca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/index.md deleted file mode 100644 index 58902c17b99..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c18318850d0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/black_box_fns.md deleted file mode 100644 index 985bb7c879d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 76745196681..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index a3780552682..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.19.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.19.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/merkle_trees.md deleted file mode 100644 index dc383a1426b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.0/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/examples/merkle-proof.mdx deleted file mode 100644 index 832fb4bb55e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/00_nargo_installation.md deleted file mode 100644 index 7d3c88c7693..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/01_hello_world.md deleted file mode 100644 index 34f8cd96fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/02_breakdown.md deleted file mode 100644 index f928370b2e8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/index.md deleted file mode 100644 index e8d86020a20..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier.md) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen Commitment -- Pedersen Hash -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/06_generics.md deleted file mode 100644 index 36c2b593fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/06_generics.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/01_integers.md deleted file mode 100644 index 1814365800a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/02_booleans.md deleted file mode 100644 index d353606210a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/03_strings.md deleted file mode 100644 index 4360893e9a2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 3c84da3f8ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index 1be0ec4a137..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/08_structs.md deleted file mode 100644 index 35421734639..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/migration_notes.md deleted file mode 100644 index 905bca3d30c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/dependencies.md deleted file mode 100644 index 87a09293ea8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/01_commands.md deleted file mode 100644 index e2b0af522f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index 64ba4a2c44a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/noir_js.md deleted file mode 100644 index f895b22eaf8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/noir_js/classes/Noir.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 3680ba3ca77..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index 1d7b54a9dca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/index.md deleted file mode 100644 index 58902c17b99..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c18318850d0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/black_box_fns.md deleted file mode 100644 index 985bb7c879d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 76745196681..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index a493d52a083..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.19.1/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.19.1/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/merkle_trees.md deleted file mode 100644 index dc383a1426b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.1/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/examples/merkle-proof.mdx deleted file mode 100644 index 832fb4bb55e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/00_nargo_installation.md deleted file mode 100644 index 7d3c88c7693..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/01_hello_world.md deleted file mode 100644 index 34f8cd96fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/02_breakdown.md deleted file mode 100644 index f928370b2e8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/index.md deleted file mode 100644 index e8d86020a20..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier.md) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen Commitment -- Pedersen Hash -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/06_generics.md deleted file mode 100644 index 36c2b593fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/06_generics.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/01_integers.md deleted file mode 100644 index 1814365800a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/02_booleans.md deleted file mode 100644 index d353606210a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/03_strings.md deleted file mode 100644 index 4360893e9a2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 3c84da3f8ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index 1be0ec4a137..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/08_structs.md deleted file mode 100644 index 9255455bdcb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/migration_notes.md deleted file mode 100644 index 905bca3d30c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/dependencies.md deleted file mode 100644 index 87a09293ea8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/01_commands.md deleted file mode 100644 index e2b0af522f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index 64ba4a2c44a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/noir_js.md deleted file mode 100644 index f895b22eaf8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/noir_js/classes/Noir.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 3680ba3ca77..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index 1d7b54a9dca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/index.md deleted file mode 100644 index 58902c17b99..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c18318850d0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/black_box_fns.md deleted file mode 100644 index 985bb7c879d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 76745196681..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index 14ce71d4d39..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.19.2/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.19.2/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/merkle_trees.md deleted file mode 100644 index dc383a1426b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.2/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/examples/merkle-proof.mdx deleted file mode 100644 index 832fb4bb55e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/00_nargo_installation.md deleted file mode 100644 index 7d3c88c7693..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/01_hello_world.md deleted file mode 100644 index 34f8cd96fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/02_breakdown.md deleted file mode 100644 index 10422029661..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter'" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/index.md deleted file mode 100644 index e8d86020a20..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier.md) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen Commitment -- Pedersen Hash -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/06_generics.md deleted file mode 100644 index 36c2b593fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/06_generics.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/01_integers.md deleted file mode 100644 index 1814365800a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/02_booleans.md deleted file mode 100644 index d353606210a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/03_strings.md deleted file mode 100644 index 4360893e9a2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 3c84da3f8ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index 1be0ec4a137..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/08_structs.md deleted file mode 100644 index 35421734639..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/migration_notes.md deleted file mode 100644 index 905bca3d30c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/dependencies.md deleted file mode 100644 index 87a09293ea8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/01_commands.md deleted file mode 100644 index e2b0af522f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index 64ba4a2c44a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/noir_js.md deleted file mode 100644 index f895b22eaf8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/noir_js/classes/Noir.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 3680ba3ca77..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,27 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index 1d7b54a9dca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/index.md deleted file mode 100644 index 58902c17b99..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,36 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 4aeff73d3e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `Uint8Array`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c18318850d0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/black_box_fns.md deleted file mode 100644 index 985bb7c879d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 76745196681..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index b4e20e091ba..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.19.3/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.19.3/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/merkle_trees.md deleted file mode 100644 index dc383a1426b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.3/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/examples/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/examples/merkle-proof.mdx deleted file mode 100644 index 832fb4bb55e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/examples/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Merkle Proof Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/00_nargo_installation.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/00_nargo_installation.md deleted file mode 100644 index 7d3c88c7693..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/00_nargo_installation.md +++ /dev/null @@ -1,249 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, - verifying and more). Learn how to install and use Nargo for your projects with this comprehensive - guide. -keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] ---- - -`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, -verifying and more). - -Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). - -### UltraPlonk - -Nargo versions \<0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk -version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. - -## Installation - -There are four approaches for installing Nargo: - -- [Option 1: Noirup](#option-1-noirup) -- [Option 2: Binaries](#option-2-binaries) -- [Option 3: Compile from Source](#option-3-compile-from-source) -- [Option 4: WSL for Windows](#option-4-wsl-for-windows) - -Optionally you can also install [Noir VS Code extension] for syntax highlighting. - -### Option 1: Noirup - -If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a -terminal and run: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done, you should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -#### GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in -this repo containing hash functions in Noir for an example. - -#### Nightly versions - -To install the nightly version of Noir (updated daily) run: - -```bash -noirup -n -``` - -### Option 2: Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --help`. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -For a successful installation, you should see something similar to the following after running the -command: - -```sh -$ nargo --help - -Noir's package manager - -Usage: nargo - -Commands: - check Checks the constraint system for errors - codegen-verifier Generates a Solidity verifier smart contract for the program - compile Compile the program and its secret execution trace into ACIR format - new Create a new binary project - execute Executes a circuit to calculate its return value - prove Create proof for this program. The proof is returned as a hex encoded string - verify Given a proof and a program, verify whether the proof is valid - test Run the tests for this program - gates Counts the occurrences of different gates in circuit - help Print this message or the help of the given subcommand(s) -``` - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#option-1-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` - -[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/01_hello_world.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/01_hello_world.md deleted file mode 100644 index 0384ba4a0cd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/01_hello_world.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Create A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -For Windows CMD, run: - -```sh -> mkdir "%USERPROFILE%\projects" -> cd /d "%USERPROFILE%\projects" -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../language_concepts/data_types.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../language_concepts/09_comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./02_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/02_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/02_breakdown.md deleted file mode 100644 index f928370b2e8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/getting_started/02_breakdown.md +++ /dev/null @@ -1,198 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies.md)for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/index.md deleted file mode 100644 index e8d86020a20..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/index.md +++ /dev/null @@ -1,100 +0,0 @@ ---- -title: Introducing Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by - Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a - rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -slug: / ---- - -## What is Noir? - -Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. - -Its design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. - -## Who is Noir for? - -Noir can be used for a variety of purposes. - -### Solidity Developers - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will -be modularized in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier.md) command to create -a verifier contract. - -### Protocol Developers - -As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for -your stack, or maybe you simply want to use a different proving system. Since Noir does not compile -to a specific proof system, it is possible for protocol developers to replace the PLONK-based -proving system with a different proving system altogether. - -### Blockchain developers - -As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the -proving system and smart contract language has been pre-defined). In order for you to use Noir in -your blockchain, a proving system backend and a smart contract interface -must be implemented for it. - -## What's new about Noir? - -Noir is simple and flexible in its design, as it does not compile immediately to a fixed -NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled -to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkworks' Marlin backend, or others). - -This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. - -## Current Features - -Compiler: - -- Module System -- For expressions -- Arrays -- Bit Operations -- Binary operations (\<, \<=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] -- Unsigned integers -- If statements -- Structures and Tuples -- Generics - -ACIR Supported OPCODES: - -- Sha256 -- Blake2s -- Schnorr signature verification -- MerkleMembership -- Pedersen Commitment -- Pedersen Hash -- HashToField - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers - -See the section on [dependencies](./modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/01_functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/01_functions.md deleted file mode 100644 index 5eb22170e54..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/01_functions.md +++ /dev/null @@ -1,225 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./08_lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/02_control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/02_control_flow.md deleted file mode 100644 index a7f85360197..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/02_control_flow.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/03_ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/03_ops.md deleted file mode 100644 index 0e35ef5e584..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/03_ops.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/04_assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/04_assert.md deleted file mode 100644 index 7427ec6cc63..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/04_assert.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/05_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/05_unconstrained.md deleted file mode 100644 index 097d6ee9894..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/05_unconstrained.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] ---- - - - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/06_generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/06_generics.md deleted file mode 100644 index 36c2b593fcd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/06_generics.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/07_mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/07_mutability.md deleted file mode 100644 index ed3fed820ec..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/07_mutability.md +++ /dev/null @@ -1,92 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/08_lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/08_lambdas.md deleted file mode 100644 index ae1e6aecab1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/08_lambdas.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/09_comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/09_comments.md deleted file mode 100644 index 3bb4d2f25a4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/09_comments.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/10_distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/10_distinct.md deleted file mode 100644 index e7ff7f5017a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/10_distinct.md +++ /dev/null @@ -1,63 +0,0 @@ ---- -title: Distinct Witnesses ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/11_shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/11_shadowing.md deleted file mode 100644 index efd743e764f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/11_shadowing.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Shadowing ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types.md deleted file mode 100644 index 74f573f7d3f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](./06_generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/00_fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/00_fields.md deleted file mode 100644 index 78d3d2af166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/00_fields.md +++ /dev/null @@ -1,165 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/01_integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/01_integers.md deleted file mode 100644 index 1814365800a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/01_integers.md +++ /dev/null @@ -1,112 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/02_booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/02_booleans.md deleted file mode 100644 index 67baa00f930..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/02_booleans.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../02_control_flow.md) and -[Assert Function](../04_assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/03_strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/03_strings.md deleted file mode 100644 index baa3f205094..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/03_strings.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with `std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape Characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world"; // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Formatted Strings - -You can prepend a string with the singular `f` token to create a formatted string. This is useful when logging, as it allows injection of local variables: - -```rust -let var = 15; -std::println(f"var {var}") // prints "var 0x0F" - -let var = -1 as u8; -std::println(f"var {var}") // prints "var 255" - -let var : i8 = -1; -std::println(f"var {var}") // prints "var -1" - -// prints "Hello -//world" -std::println(f"Hello -world"); - -std::println(f"hey \tyou"); // prints "hey \tyou" -``` - -A type can be specified to print numbers either as hex via `Field`, unsigned via `u*` types and signed via `i*` types. - -Note that escaped characters in formatted strings `fmtstr` will be outputted as defined, i.e. "\n" will be printed `\n`, not as a new line. You can add a newline or other whitespace by creating a multiline string as in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/04_arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/04_arrays.md deleted file mode 100644 index 36410468ec1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/04_arrays.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./05_slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/05_slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/05_slices.mdx deleted file mode 100644 index 1be0ec4a137..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/05_slices.mdx +++ /dev/null @@ -1,146 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/06_vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/06_vectors.mdx deleted file mode 100644 index 4617e90d038..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/06_vectors.mdx +++ /dev/null @@ -1,172 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/07_tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/07_tuples.md deleted file mode 100644 index 5f6cab974a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/07_tuples.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/08_structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/08_structs.md deleted file mode 100644 index 35421734639..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/08_structs.md +++ /dev/null @@ -1,69 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/09_references.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/09_references.md deleted file mode 100644 index b0c35ce2cb9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/09_references.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: References ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/10_function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/10_function_types.md deleted file mode 100644 index 1ec92efd594..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/language_concepts/data_types/10_function_types.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Function types ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../08_lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/migration_notes.md deleted file mode 100644 index 905bca3d30c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 23f60855c30..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/dependencies.md deleted file mode 100644 index 753b6038703..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/04_ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/modules.md deleted file mode 100644 index 11e60cbf35e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/modules.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/workspaces.md deleted file mode 100644 index 8168793fc80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -title: Workspaces ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/01_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/01_commands.md deleted file mode 100644 index 914856a0f43..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/01_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Commands -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--include-keys` | Include Proving and Verification keys in the build artifacts | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](./02_testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/02_testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/02_testing.md deleted file mode 100644 index 5c57ef92705..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/02_testing.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/03_solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/03_solidity_verifier.md deleted file mode 100644 index 9ac60cb0ba7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/03_solidity_verifier.md +++ /dev/null @@ -1,129 +0,0 @@ ---- -title: Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out! -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/04_language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/04_language_server.md deleted file mode 100644 index 48c01465f6e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/nargo/04_language_server.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/getting_started/01_tiny_noir_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/getting_started/01_tiny_noir_app.md deleted file mode 100644 index 64ba4a2c44a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/getting_started/01_tiny_noir_app.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -title: End-to-end -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/noir_js.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/noir_js.md deleted file mode 100644 index f895b22eaf8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/noir_js.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: NoirJS -description: Interact with Noir in Typescript or Javascript -keywords: [Noir project, javascript, typescript, node.js, browser, react] ---- - -NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. - -A typical workflow would be composed of two major elements: - -- NoirJS -- Proving backend of choice's JavaScript package - - - -To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: - -```bash -npm i @noir-lang/noir_js -``` - -## Proving backend - -Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. - -### Barretenberg - -Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. - -To install its JavaScript library, run this in your project: - -```bash -npm i @noir-lang/backend_barretenberg -``` - -For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/noir_js/classes/Noir.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 93b248b0f65..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,45 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -## Functions - -### flattenPublicInputs() - -```ts -flattenPublicInputs(publicInputs): string[] -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `WitnessMap` | - -#### Returns - -`string`[] - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index c54468891af..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/index.md deleted file mode 100644 index 348453c0059..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [InputMap](type-aliases/InputMap.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/InputMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/InputMap.md deleted file mode 100644 index c714e999d93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/InputMap.md +++ /dev/null @@ -1,13 +0,0 @@ -# InputMap - -```ts -type InputMap: object; -``` - -## Index signature - - \[`key`: `string`\]: `InputValue` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index 077ebeb133e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/InputMap","label":"InputMap"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/black_box_fns.md deleted file mode 100644 index b115a450ed3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/00_hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/02_schnorr.mdx) -- [Blake2s](./cryptographic_primitives/00_hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/00_hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/00_hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/00_hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/03_ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/01_scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/00_hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives.md deleted file mode 100644 index 2df4f929474..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic primitives in Noir -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/00_hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/00_hashes.mdx deleted file mode 100644 index 76745196681..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/00_hashes.mdx +++ /dev/null @@ -1,167 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/01_scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/01_scalar.mdx deleted file mode 100644 index c7eed820a80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/01_scalar.mdx +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/02_schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/02_schnorr.mdx deleted file mode 100644 index c184ce28120..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/02_schnorr.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx deleted file mode 100644 index 72bce984821..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/04_ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/04_ec_primitives.md deleted file mode 100644 index 6f69e468402..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/04_ec_primitives.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.19.4/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.19.4/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/05_eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/05_eddsa.mdx deleted file mode 100644 index 9a5beb55ee9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/cryptographic_primitives/05_eddsa.mdx +++ /dev/null @@ -1,17 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/logging.md deleted file mode 100644 index 4ba0fe0e656..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/logging.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides a familiar `println` statement you can use. Despite being a limited -implementation of rust's `println!` macro, this construct can be useful for debugging. - -You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. - -The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} - -``` - -You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/merkle_trees.md deleted file mode 100644 index dc383a1426b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/recursion.md deleted file mode 100644 index 5e592a2fd89..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/recursion.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Aggregation Object - -The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). - -So for example in this circuit: - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key, - proof, - public_inputs, - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key, - proof_b, - public_inputs, - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.19.4/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explainers/explainer-recursion.md deleted file mode 100644 index 9357d3c7341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,175 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation Objects", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -So, Alice started thinking: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -So, the tallier puts all the votes in a merkle tree, and everyone can also prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He could find it more efficient to generate a proof for that setup phase separately, and verifying it in his actual business logic section of the circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof -- The input aggregation object - -It also returns the `output aggregation object`. These aggregation objects can be confusing at times, so let's dive in a little bit. - -### Aggregation objects - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he is verifying a proof, so it needs to output an `aggregation object`: he is generating a recursive proof! -- Alice verifies Bob's *recursive proof*, and uses Bob's `output aggregation object` as the `input aggregation object` in her proof... Which in turn, generates another `output aggregation object`. - -One should notice that when Bob generates his first proof, he has no input aggregation object. Because he is not verifying an recursive proof, he has no `input aggregation object`. In this case, he may use zeros instead. - -We can imagine the `aggregation object` as the baton in a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/noir/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/noir/traits.md deleted file mode 100644 index 7ba07e74f40..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/noir/traits.md +++ /dev/null @@ -1,348 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/standard_library/traits.md deleted file mode 100644 index 63b4f3d6f0b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/explanations/standard_library/traits.md +++ /dev/null @@ -1,140 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust -trait Default { - fn default() -> Self; -} -``` - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type. - -## `std::ops` - -### `std::ops::Eq` - -```rust -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -Returns `true` if `self` is equal to `other`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Although Noir does not currently have operator overloading, in the future implementing these -traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust -trait Add { - fn add(self, other: Self) -> Self; -} - -trait Sub { - fn sub(self, other: Self) -> Self; -} - -trait Mul { - fn mul(self, other: Self) -> Self; -} - -trait Div { - fn div(self, other: Self) -> Self; -} -``` - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/create_a_project.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/create_a_project.md deleted file mode 100644 index f10916c39c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/create_a_project.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating A Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ that contains the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../noir/syntax/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../noir/syntax/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution on our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/index.md deleted file mode 100644 index ddb8a250eb4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/index.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo though the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index a532f83750e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: Alternative Install Methods -description: - There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains other methods that don't rely on noirup, such as compiling from source, installing from binaries, and using WSL for windows -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Shell & editor experience - Building and testing - Uninstalling Nargo - Noir vs code extension -] -sidebar_position: 1 ---- - - -## Installation - -The most common method of installing Nargo is through [Noirup](./index.md) - -However, there are other methods for installing Nargo: - -- [Binaries](#binaries) -- [Compiling from Source](#compile-from-source) -- [WSL for Windows](#wsl-for-windows) - -### Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --version`. You should get a version number. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](./index.md). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/project_breakdown.md deleted file mode 100644 index c4e2a9ae003..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program in section _1.2_. We elaborate on the project -structure and what the `prove` and `verify` commands did in the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section requires a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` - is not equal. This not equal constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs from usually external sources and -verifies the validity of the proof against it. - -Take a private asset transfer as an example: - -A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/_category_.json deleted file mode 100644 index dff520ebc41..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 3, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/index.md deleted file mode 100644 index 16f5f3ca45e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/index.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/how-to-recursion.md deleted file mode 100644 index 2f7be604401..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. Meaning it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. Which means these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume these two: - -- `main`: a circuit of type `assert(x != y)` -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateIntermediateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit are we actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*. So it is Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyIntermediateProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate the intermediate artifacts: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateIntermediateProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]`. However, currently the backend doesn't remove the public inputs from the proof when converting it. - -This means that if your `main` circuit has two public inputs, then you should also modify the recursive circuit to accept a proof with the public inputs appended. This means that in our example, since `y` is a public input, our `proofAsFields` is of type `[Field; 94]`. - -Verification keys in Barretenberg are always of size 114. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, - input_aggregation_object: Array(16).fill(0) // this circuit is verifying a non-recursive proof, so there's no input aggregation object: just use zero -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateFinalProof(witness) -const verified = backend.verifyFinalProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! In that case, you should keep in mind the `returnValue`, as it will contain the `input_aggregation_object` for the next proof. - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { -main: mainJSON, -recursive: recursiveJSON -} -const backends = { -main: new BarretenbergBackend(circuits.main), -recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { -main: new Noir(circuits.main, backends.main), -recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateIntermediateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyIntermediateProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateIntermediateProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateFinalProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/merkle-proof.mdx deleted file mode 100644 index 34074659ac1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/solidity_verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/solidity_verifier.md deleted file mode 100644 index 6aaad542ee0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/how_to/solidity_verifier.md +++ /dev/null @@ -1,131 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 ---- - -For certain applications, it may be desirable to run the verifier as a smart contract instead of on -a local machine. - -Compile a Solidity verifier contract for your Noir program by running: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. - -> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract -> platforms as long as the proving backend supplies an implementation. -> -> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in -> Solidity only for the time being. - -## Verify - -To verify a proof using the Solidity verifier contract, call the `verify` function with the -following signature: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -### Public Inputs - -:::tip - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -::: - -The verifier contract uses the output (return) value of a Noir program as a public input. So if you -have the following function - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an -error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. - -#### Struct inputs - -Consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -## Noir for EVM chains - -You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo -- Taiko - -Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -### Unsupported chains - -Unfortunately not all "EVM" chains are supported. - -**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/index.md deleted file mode 100644 index eaf8c59f935..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/index.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: Noir -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [ - Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language, - ] -sidebar_position: 0 ---- - -## What's new about Noir? - -Noir, a domain-specific language crafted for SNARK proving systems, stands out with its simplicity, flexibility, -and robust capabilities. Unlike conventional approaches that compile directly to a fixed NP-complete language, -Noir takes a two-pronged path. It first compiles to an adaptable intermediate language known as ACIR. From there, -depending on the project's needs, ACIR can be further compiled into an arithmetic circuit for integration with Aztec's -barretenberg backend or transformed into a rank-1 constraint system suitable for R1CS backends like Arkworks' Marlin -backend, among others. - -This innovative design introduces unique challenges, yet it strategically separates the programming language from the -backend. Noir's approach echoes the modular philosophy of LLVM, offering developers a versatile toolkit for cryptographic -programming. - -## Who is Noir for? - -### Solidity Developers - -Noir streamlines the creation of Solidity contracts that interface with SNARK systems. -[`Utilize the nargo codegen-verifier`](./reference/nargo_commands.md#nargo-codegen-verifier) command to construct verifier -contracts efficiently. While the current alpha version offers this as a direct feature, future updates aim -to modularize this process for even greater ease of use. - -Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will be -modularized in the future; however, as of the alpha, you can use the `nargo codegen-verifier` command to create a verifier contract. - -### Protocol Developers - -Should the Aztec backend not align with your existing tech stack, or if you're inclined to integrate alternative -proving systems, Noir's agnostic compilation to a proof-agnostic intermediate language offers unmatched flexibility. -This allows protocol engineers the freedom to substitute the default PLONK-based system with an alternative of their -choice, tailoring the proving system to their specific needs. - -### Blockchain developers - -Blockchain developers often face environmental constraints, such as predetermined proving systems and smart contract -languages. Noir addresses this by enabling the implementation of custom proving system backends and smart contract -interfaces, ensuring seamless integration with your blockchain's architecture, and expanding the horizons for innovation -within your projects. - -## Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the -[awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains - the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage - proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing - for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and - return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of - sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data - type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, - allowing results that aren't whole numbers - -See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/migration_notes.md deleted file mode 100644 index 9c1809fd609..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/syntax/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index d9d21ef0485..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index 985bb7c879d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -:::warning - -It is likely that not all backends will support a particular black box function. - -::: - -Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. - -Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: - -```rust -#[foreign(sha256)] -fn sha256(_input : [u8; N]) -> [u8; 32] {} -``` - -## Function list - -Here is a list of the current black box functions that are supported by UltraPlonk: - -- AES -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [HashToField128Security](./cryptographic_primitives/hashes.mdx#hash_to_field) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- [Compute merkle root](./merkle_trees.md#compute_merkle_root) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index fc8ed59f09d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.22.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.22.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 1376c51dfde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust -fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool -``` - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index a9c10da6c06..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 9250cb4a0c0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,168 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust -fn sha256(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust -fn blake2s(_input : [u8]) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust -fn pedersen_hash(_input : [Field]) -> Field -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen_hash(x); -} -``` - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust -fn pedersen_commitment(_input : [Field]) -> [Field; 2] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let commitment = std::hash::pedersen_commitment(x); -} -``` - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust -fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] -``` - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let message_size = 4; - let hash = std::hash::keccak256(x, message_size); -} -``` - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust -fn main() -{ - let hash_2 = std::hash::poseidon::bn254::hash_2([1, 2]); - assert(hash2 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); -} -``` - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index 1e686303c18..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust -fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] -``` - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - std::println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index 7a2c9c20226..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,38 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust -fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool -``` - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/logging.md deleted file mode 100644 index 2e163b52ab3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/logging.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -use dep::std; - -struct Person { - age : Field, - height : Field, -} - -fn main(age : Field, height : Field) { - let person = Person { age : age, height : height }; - std::println(person); - std::println(age + height); - std::println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - std::println(fmt_str); - - let s = myStruct { y: x, x: y }; - std::println(s); - - std::println(f"i: {i}, s: {s}"); - - std::println(x); - std::println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - std::println(f"s: {s}, foo: {foo}"); - - std::println(15); // prints 0x0f, implicit Field - std::println(-1 as u8); // prints 255 - std::println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -std::println(person); -std::print(person); - -std::println("Hello world!"); // Prints with a newline at the end of the input -std::print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 5b45617812a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - std::println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/options.md deleted file mode 100644 index 3d3139fb98b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/options.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -You can import the Option type into your Noir program like so: - -```rust -use dep::std::option::Option; - -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/recursion.md deleted file mode 100644 index 4a004fd3664..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,90 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 94], - public_inputs : [Field; 1], - key_hash : Field, - input_aggregation_object : [Field; 16], - proof_b : [Field; 94], -) -> pub [Field; 16] { - let output_aggregation_object_a = std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash, - input_aggregation_object - ); - - let output_aggregation_object = std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash, - output_aggregation_object_a - ); - - let mut output = [0; 16]; - for i in 0..16 { - output[i] = output_aggregation_object[i]; - } - output -} -``` - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. - -### `input_aggregation_object` - -An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. - -## Return value - -### `output_aggregation_object` - -This is the result of a recursive aggregation and is what will be fed into the next verifier. -The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. - -## Example - -You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/_category_.json deleted file mode 100644 index 666b691ae91..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Syntax", - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/assert.md deleted file mode 100644 index c5f9aff139c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/assert.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/comments.md deleted file mode 100644 index f76ab49094b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 9 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/control_flow.md deleted file mode 100644 index 4ce65236db3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/control_flow.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_bus.md deleted file mode 100644 index 6c7e9b60891..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 12 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/arrays.md deleted file mode 100644 index addda1da8bc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/arrays.md +++ /dev/null @@ -1,245 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/fields.md deleted file mode 100644 index a1c67945d66..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/fields.md +++ /dev/null @@ -1,166 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/index.md deleted file mode 100644 index f09bca0ee04..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/integers.md deleted file mode 100644 index baf5f4742c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/integers.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/slices.mdx deleted file mode 100644 index 4a6ee816aa2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/slices.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/strings.md deleted file mode 100644 index dd6c844f6ae..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`std::println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - std::println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/vectors.mdx deleted file mode 100644 index 10e35711b74..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/data_types/vectors.mdx +++ /dev/null @@ -1,173 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -use dep::std::collections::vec::Vec; - -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/distinct.md deleted file mode 100644 index b59e0296b23..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 10 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/functions.md deleted file mode 100644 index 48aba9cd058..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/generics.md deleted file mode 100644 index d59e4c5d7c6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/generics.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 6 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn new(value: T) -> Self { - Self { value, count: 1 } - } - - fn increment(mut repeated: Self) -> Self { - repeated.count += 1; - repeated - } - - fn print(self) { - for _i in 0 .. self.count { - dep::std::println(self.value); - } - } -} - -fn main() { - let mut repeated = RepeatedValue::new("Hello!"); - repeated = repeated.increment(); - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in -Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also -requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? - -The answer is that we can translate this by passing in the function manually. Here's an example of -implementing array equality in Noir: - -```rust -fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { - if array1.len() != array2.len() { - false - } else { - let mut result = true; - for i in 0 .. array1.len() { - result &= elem_eq(array1[i], array2[i]); - } - result - } -} - -fn main() { - assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); - - // We can use array_eq even for arrays of structs, as long as we have - // an equality function for these structs we can pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} -``` - -You can see an example of generics in the tests -[here](https://github.com/noir-lang/noir/blob/master/test_programs/execution_success/generics/src/main.nr). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/lambdas.md deleted file mode 100644 index e0a267adfda..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 8 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/mutability.md deleted file mode 100644 index 6abfae3cfa7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/mutability.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] -sidebar_position: 7 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/shadowing.md deleted file mode 100644 index b5a6b6b38b9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 11 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/unconstrained.md deleted file mode 100644 index 6b3424f7993..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/noir/syntax/unconstrained.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index bfbecb52864..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,45 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -## Functions - -### flattenPublicInputs() - -```ts -flattenPublicInputs(publicInputs): string[] -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `WitnessMap` | - -#### Returns - -`string`[] - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 2aaa55bccf6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 34e20d99684..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index 8b9e35bc9a1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [InputMap](type-aliases/InputMap.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/InputMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/InputMap.md deleted file mode 100644 index c714e999d93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/InputMap.md +++ /dev/null @@ -1,13 +0,0 @@ -# InputMap - -```ts -type InputMap: object; -``` - -## Index signature - - \[`key`: `string`\]: `InputValue` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index fe2629ddc9f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/InputMap","label":"InputMap"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/nargo_commands.md deleted file mode 100644 index ff3dee8973f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/reference/nargo_commands.md +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](../getting_started/tooling/testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.22.0/tutorials/noirjs_app.md deleted file mode 100644 index 516e07c89fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.22.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,261 +0,0 @@ ---- -title: Tiny NoirJS app -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] -sidebar_position: 0 ---- - -NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Before we start - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. - -In this guide, we will be pinned to 0.17.0. - -::: - -Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). - -First of all, follow the [Nargo guide](../getting_started/installation/index.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: - -```bash -nargo compile -``` - -Your folder structure should look like: - -```tree -. -└── circuit - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -## Starting a new project - -Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. - -## Installing dependencies - -We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: - -```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 -``` - -To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: - -```bash -npm i --save-dev vite rollup-plugin-copy -``` - -Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: - -```json - "start": "vite --open" -``` - -If you want do build a static website, you can also add some build and preview scripts: - -```json - "build": "vite build", - "preview": "vite preview" -``` - -## Vite plugins - -Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. - -```js -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -## HTML - -Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: - -```html - - - - - - -

Very basic Noir app

-
-

Logs

-

Proof

-
- - -``` - -## Some good old vanilla Javascript - -Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: - -```js -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} -``` - -We can manipulate our website with this little function, so we can see our website working. - -## Adding Noir - -If you come from the previous page, your folder structure should look like this: - -```tree -├── app.js -├── circuit -│ ├── Nargo.toml -│ ├── src -│ │ └── main.nr -│ └── target -│ └── circuit.json -├── index.html -├── package.json -└── vite.config.js -``` - -You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. - -## Importing our dependencies - -We're starting with the good stuff now. At the top of the new javascript file, import the packages: - -```ts -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: - -```ts -import circuit from './circuit/target/circuit.json'; -``` - -## Write code - -:::note - -We're gonna be adding code inside the `document.addEventListener...etc` block: - -```js -// forget stuff here -document.addEventListener('DOMContentLoaded', async () => { - // here's where the magic happens -}); -// forget stuff here -``` - -::: - -Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: - -```ts -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -``` - -## Proving - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -const input = { x: 1, y: 2 }; -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. - -In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -By saving, your app will refresh and here's our complete Tiny Noir App! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 746633b628d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: Alternative Install Methods -description: - There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains other methods that don't rely on noirup, such as compiling from source, installing from binaries, and using WSL for windows -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Shell & editor experience - Building and testing - Uninstalling Nargo - Noir vs code extension -] -sidebar_position: 1 ---- - - -## Installation - -The most common method of installing Nargo is through [Noirup](./index.md) - -However, there are other methods for installing Nargo: - -- [Binaries](#binaries) -- [Compiling from Source](#compile-from-source) -- [WSL for Windows](#wsl-for-windows) - -### Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.23.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.23.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.23.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --version`. You should get a version number. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -### Option 3: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 4: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](./index.md). - -## Uninstalling Nargo - -### Noirup - -If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/_category_.json deleted file mode 100644 index 55804c03a71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 2, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/index.mdx deleted file mode 100644 index ec9ccea4115..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - - - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-oracles.md deleted file mode 100644 index 0d84d992320..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,280 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map(({ inner }) => { - return { inner: `${Math.sqrt(parseInt(inner, 16))}` }; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a `inner` property *as a string*. For example: - -```json -{ "values": [{ "Array": [{ "inner": "1" }, { "inner": "2"}]}]} -{ "values": [{ "Single": { "inner": "1" }}]} -{ "values": [{ "Single": { "inner": "1" }}, { "Array": [{ "inner": "1", { "inner": "2" }}]}]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface Value { - inner: string, -} - -interface SingleForeignCallParam { - Single: Value, -} - -interface ArrayForeignCallParam { - Array: Value[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateFinalProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => ({ inner: i.toString("hex") })) }, - ]); - return [oracleReturn.values[0].Array.map((x) => x.inner)]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-recursion.md deleted file mode 100644 index f34647a99d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume these two: - -- `main`: a circuit of type `assert(x != y)` -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateIntermediateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyIntermediateProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate the intermediate artifacts: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateIntermediateProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateFinalProof(witness) -const verified = backend.verifyFinalProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateIntermediateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyIntermediateProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateIntermediateProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateFinalProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/merkle-proof.mdx deleted file mode 100644 index 34074659ac1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/migration_notes.md deleted file mode 100644 index 68acd5e566e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/migration_notes.md +++ /dev/null @@ -1,107 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## 0.22.0 - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/assert.md deleted file mode 100644 index c5f9aff139c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/assert.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/control_flow.md deleted file mode 100644 index 4ce65236db3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index fb81dcc3970..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = []; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays: - -### len - -Returns the length of an array - -```rust -fn len(_array: [T; N]) -> comptime Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(_array: [T; N]) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/fields.md deleted file mode 100644 index 99b4aa63549..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/index.md deleted file mode 100644 index f09bca0ee04..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 30135d76e4a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4a6ee816aa2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/vectors.mdx deleted file mode 100644 index aed13183719..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/data_types/vectors.mdx +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/functions.md deleted file mode 100644 index 48aba9cd058..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/mutability.md deleted file mode 100644 index 9cc10429cb4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/mutability.md +++ /dev/null @@ -1,93 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables, constants, and globals in Noir programming language. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Comptime Values - -:::warning - -The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. - -::: - -## Globals - -Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array -annotations for function parameters and can be imported from submodules. - -```rust -global N: Field = 5; // Same as `global N: Field = 5` - -fn main(x : Field, y : [Field; N]) { - let res = x * N; - - assert(res == y[0]); - - let res2 = x * my_submodule::N; - assert(res != res2); -} - -mod my_submodule { - use dep::std; - - global N: Field = 10; - - fn my_helper() -> Field { - let x = N; - x - } -} -``` - -## Why only local mutability? - -Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting -without applying additional overhead to the user. Modeling a mutable reference is not as -straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/oracles.md deleted file mode 100644 index 2e6a6818d48..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/oracles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/unconstrained.md deleted file mode 100644 index 6b3424f7993..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index d9d21ef0485..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 8067d38d465..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.23.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.23.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4bf09cef178..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index a9c10da6c06..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 730b6d4117f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L5-L7 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L11-L13 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L17-L19 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L42-L44 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint -``` -> Source code: noir_stdlib/src/hash.nr#L22-L29 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L67-L69 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L11 - - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index ae12e6c12dc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index fa488677884..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/options.md deleted file mode 100644 index 970c9cfbf11..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/options.md +++ /dev/null @@ -1,97 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/recursion.md deleted file mode 100644 index 4390bda4a26..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/traits.md deleted file mode 100644 index f2960ca5080..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/traits.md +++ /dev/null @@ -1,284 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust -trait Default { - fn default() -> Self; -} -``` - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type. - -## `std::cmp` - -### `std::cmp::Eq` - -```rust -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Cmp` - -```rust -trait Cmp { - fn cmp(self, other: Self) -> Ordering; -} -``` - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust -trait Add { - fn add(self, other: Self) -> Self; -} - -trait Sub { - fn sub(self, other: Self) -> Self; -} - -trait Mul { - fn mul(self, other: Self) -> Self; -} - -trait Div { - fn div(self, other: Self) -> Self; -} -``` - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust -trait Rem { - fn rem(self, other: Self) -> Self; -} -``` - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust -trait BitOr { - fn bitor(self, other: Self) -> Self; -} - -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} - -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust -trait Shl { - fn shl(self, other: Self) -> Self; -} - -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/index.md deleted file mode 100644 index 93b248b0f65..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/index.md +++ /dev/null @@ -1,45 +0,0 @@ -# Backend Barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -## Functions - -### flattenPublicInputs() - -```ts -flattenPublicInputs(publicInputs): string[] -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `WitnessMap` | - -#### Returns - -`string`[] - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 04e662c845f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/classes/Noir.md deleted file mode 100644 index c54468891af..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/classes/Noir.md +++ /dev/null @@ -1,131 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 0ba5783f0d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,29 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/index.md deleted file mode 100644 index 348453c0059..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# Noir JS - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [InputMap](type-aliases/InputMap.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Calculates the Blake2s256 hash of the input bytes and represents these as a single field element. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/InputMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/InputMap.md deleted file mode 100644 index c714e999d93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/InputMap.md +++ /dev/null @@ -1,13 +0,0 @@ -# InputMap - -```ts -type InputMap: object; -``` - -## Index signature - - \[`key`: `string`\]: `InputValue` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 3eb360a78f1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `WitnessMap` | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index 077ebeb133e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/noir_js/reference/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"noir_js/reference/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/InputMap","label":"InputMap"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"noir_js/reference/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"noir_js/reference/noir_js/functions/and","label":"and"},{"type":"doc","id":"noir_js/reference/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"noir_js/reference/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"noir_js/reference/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index 5cbe9421b92..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,185 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateFinalProof`](../interfaces/Backend.md#generatefinalproof) - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(witness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `witness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProof`](../interfaces/Backend.md#generateintermediateproof) - -#### Example - -```typescript -const intermediateProof = await backend.generateIntermediateProof(witness); -``` - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`generateIntermediateProofArtifacts`](../interfaces/Backend.md#generateintermediateproofartifacts) - -#### Example - -```typescript -const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyFinalProof`](../interfaces/Backend.md#verifyfinalproof) - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`verifyIntermediateProof`](../interfaces/Backend.md#verifyintermediateproof) - -#### Example - -```typescript -const isValidIntermediate = await backend.verifyIntermediateProof(proof); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index e32501acb71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,46 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): WitnessMap -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -`WitnessMap` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index 266ade75d17..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,19 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 05cebbc4e94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `string`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 2aaa55bccf6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 34e20d99684..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateFinalProof() - -```ts -generateFinalProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateFinalProof(input) -``` - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyFinalProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index d600e21b299..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [InputMap](type-aliases/InputMap.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/InputMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/InputMap.md deleted file mode 100644 index c714e999d93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/InputMap.md +++ /dev/null @@ -1,13 +0,0 @@ -# InputMap - -```ts -type InputMap: object; -``` - -## Index signature - - \[`key`: `string`\]: `InputValue` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 05cebbc4e94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `string`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index fe2629ddc9f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/InputMap","label":"InputMap"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 33eb434c3db..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`CompilationResult`](../type-aliases/CompilationResult.md)\> - -## Example - -```typescript -// Node.js - -import { compile, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile(fm); -``` - -```typescript -// Browser - -import { compile, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index 939f2481687..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,21 +0,0 @@ -# noir_wasm - -## Exports - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompilationResult](type-aliases/CompilationResult.md) | output of Noir Wasm compilation, can be for a contract or lib/binary | - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/type-aliases/CompilationResult.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/type-aliases/CompilationResult.md deleted file mode 100644 index 23cfbe6025d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/type-aliases/CompilationResult.md +++ /dev/null @@ -1,11 +0,0 @@ -# CompilationResult - -```ts -type CompilationResult: ContractCompilationArtifacts | ProgramCompilationArtifacts; -``` - -output of Noir Wasm compilation, can be for a contract or lib/binary - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index d7eba0db813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/type-aliases/CompilationResult","label":"CompilationResult"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/nargo_commands.md deleted file mode 100644 index fc2671b2bfc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/reference/nargo_commands.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -## General options - -| Option | Description | -| -------------------- | -------------------------------------------------- | -| `--show-ssa` | Emit debug information for the intermediate SSA IR | -| `--deny-warnings` | Quit execution when warnings are emitted | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo help [subcommand]` - -Prints the list of available commands or specific information of a subcommand. - -_Arguments_ - -| Argument | Description | -| -------------- | -------------------------------------------- | -| `` | The subcommand whose help message to display | - -## `nargo backend` - -Installs and selects custom backends used to generate and verify proofs. - -### Commands - -| Command | Description | -| ----------- | --------------------------------------------------------- | -| `current` | Prints the name of the currently active backend | -| `ls` | Prints the list of currently installed backends | -| `use` | Select the backend to use | -| `install` | Install a new backend from a URL | -| `uninstall` | Uninstalls a backend | -| `help` | Print this message or the help of the given subcommand(s) | - -### Options - -| Option | Description | -| ------------ | ----------- | -| `-h, --help` | Print help | - -## `nargo check` - -Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output -values of the Noir program respectively. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to check | -| `--workspace` | Check all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -### `nargo codegen-verifier` - -Generate a Solidity verifier smart contract for the program. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------- | -| `--package ` | The name of the package to codegen | -| `--workspace` | Codegen all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo compile` - -Compile the program into a JSON build artifact file containing the ACIR representation and the ABI -of the circuit. This build artifact can then be used to generate and verify proofs. - -You can also use "build" as an alias for compile (e.g. `nargo build`). - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `--package ` | The name of the package to compile | -| `--workspace` | Compile all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo new ` - -Creates a new Noir project in a new folder. - -**Arguments** - -| Argument | Description | -| -------- | -------------------------------- | -| `` | The path to save the new project | - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: package directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo init` - -Creates a new Noir project in the current directory. - -### Options - -| Option | Description | -| --------------- | ----------------------------------------------------- | -| `--name ` | Name of the package [default: current directory name] | -| `--lib` | Use a library template | -| `--bin` | Use a binary template [default] | -| `--contract` | Use a contract template | -| `-h, --help` | Print help | - -## `nargo execute [WITNESS_NAME]` - -Runs the Noir program and prints its return value. - -**Arguments** - -| Argument | Description | -| ---------------- | ----------------------------------------- | -| `[WITNESS_NAME]` | Write the execution witness to named file | - -### Options - -| Option | Description | -| --------------------------------- | ------------------------------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `--package ` | The name of the package to execute | -| `--workspace` | Execute all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `--oracle-resolver` | JSON RPC url to solve oracle calls | -| `-h, --help` | Print help | - -_Usage_ - -The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which -must be filled in. - -To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A -`.tr` file will then be saved in the `./target` folder. - -## `nargo prove` - -Creates a proof for the program. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--verify` | Verify proof after proving | -| `--package ` | The name of the package to prove | -| `--workspace` | Prove all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `--oracle-resolver` | JSON RPC url to solve oracle calls | -| `-h, --help` | Print help | - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid. - -### Options - -| Option | Description | -| ------------------------------------- | ---------------------------------------------------------------------------------------- | -| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | -| `--package ` | The name of the package to verify | -| `--workspace` | Verify all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -## `nargo test [TEST_NAME]` - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. - -Takes an optional `--exact` flag which allows you to select tests based on an exact name. - -See an example on the [testing page](../getting_started/tooling/testing.md). - -### Options - -| Option | Description | -| --------------------- | -------------------------------------- | -| `--show-output` | Display output of `println` statements | -| `--exact` | Only run tests that match exactly | -| `--package ` | The name of the package to test | -| `--workspace` | Test all packages in the workspace | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `--oracle-resolver` | JSON RPC url to solve oracle calls | -| `-h, --help` | Print help | - -## `nargo info` - -Prints a table containing the information of the package. - -Currently the table provide - -1. The number of ACIR opcodes -2. The final number gates in the circuit used by a backend - -If the file contains a contract the table will provide the -above information about each function of the contract. - -## `nargo lsp` - -Start a long-running Language Server process that communicates over stdin/stdout. -Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). - -## `nargo fmt` - -Automatically formats your Noir source code based on the default formatting settings. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.23.0/tutorials/noirjs_app.md deleted file mode 100644 index e3bc8c58b24..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.23.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,295 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.23.x matches `noir_js@0.23.x`, etc. - -In this guide, we will be pinned to 0.23.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to *anyone* is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -```nargo new circuit``` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -```nargo compile``` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -You should see `vite-project` appear in your root folder. This seems like a good time to `cd` into it and install our NoirJS packages: - -```bash -npm i @noir-lang/backend_barretenberg@0.23.0 @noir-lang/noir_js@0.23.0 vite-plugin-top-level-await -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -Add a `vite.config.js` file containing the following: - -```js -import { defineConfig } from 'vite'; -import topLevelAwait from "vite-plugin-top-level-await"; - -export default defineConfig({ - plugins: [ - topLevelAwait({ - promiseExportName: "__tla", - promiseImportName: i => `__tla_${i}` - }) - ] -}) -``` - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It *could* be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import("@noir-lang/noirc_abi").then(module => - module.default(new URL("@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm", import.meta.url).toString()) - ), - import("@noir-lang/acvm_js").then(module => - module.default(new URL("@noir-lang/acvm_js/web/acvm_js_bg.wasm", import.meta.url).toString()) - ) - ]); -} - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch(err) { - display("logs", "Oh 💔 Wrong guess") - } -}); - -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateFinalProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyFinalProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 076f26dfd94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,254 +0,0 @@ ---- -title: Alternative Install Methods -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains other methods that don't rely on noirup, such as compiling from source, installing from binaries, and using WSL for windows -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Shell & editor experience - Building and testing - Uninstalling Nargo - Noir vs code extension, - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Alternate Installation Methods (No Longer Recommended) - -While the following methods are available, they are no longer recommended. We advise using noirup for a more efficient and flexible installation experience. - -However, there are other methods for installing Nargo: - -- [Binaries](#option-1-installing-from-binaries) -- [Compiling from Source](#option-2-compile-from-source) -- [WSL for Windows](#option-3-wsl-for-windows) - -### Option 1: Installing from Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --version`. You should get a version number. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -### Option 2: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 3: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Nargo with `noirup` or through directly downloading binaries, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Nargo with Nix or compiled it from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/_category_.json deleted file mode 100644 index 55804c03a71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 2, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/index.mdx deleted file mode 100644 index ec9ccea4115..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - - - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-oracles.md deleted file mode 100644 index ab225b9421f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,280 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map(({ inner }) => { - return { inner: `${Math.sqrt(parseInt(inner, 16))}` }; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a `inner` property *as a string*. For example: - -```json -{ "values": [{ "Array": [{ "inner": "1" }, { "inner": "2"}]}]} -{ "values": [{ "Single": { "inner": "1" }}]} -{ "values": [{ "Single": { "inner": "1" }}, { "Array": [{ "inner": "1", { "inner": "2" }}]}]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface Value { - inner: string, -} - -interface SingleForeignCallParam { - Single: Value, -} - -interface ArrayForeignCallParam { - Array: Value[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => ({ inner: i.toString("hex") })) }, - ]); - return [oracleReturn.values[0].Array.map((x) => x.inner)]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/merkle-proof.mdx deleted file mode 100644 index 34074659ac1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/migration_notes.md deleted file mode 100644 index 9f27230a1a0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/migration_notes.md +++ /dev/null @@ -1,91 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/control_flow.md deleted file mode 100644 index 4ce65236db3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9a4c485feb1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = []; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/fields.md deleted file mode 100644 index 99b4aa63549..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/index.md deleted file mode 100644 index f09bca0ee04..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,96 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 30135d76e4a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,162 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports arbitrarily-sized, both unsigned and signed integer types. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -:::tip - -If you are using the default proving backend with Noir, both even (e.g. _u2_, _i2_) and odd (e.g. _u3_, _i3_) arbitrarily-sized integer types up to 127 bits (i.e. _u127_ and _i127_) are supported. - -::: - - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4a6ee816aa2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/vectors.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/vectors.mdx deleted file mode 100644 index aed13183719..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/data_types/vectors.mdx +++ /dev/null @@ -1,171 +0,0 @@ ---- -title: Vectors -description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self { - Self { slice: [] } -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self { - Self { slice } -} -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T { - self.slice[index] -} -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) { - self.slice = self.slice.push_back(elem); -} -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T { - let (popped_slice, last_elem) = self.slice.pop_back(); - self.slice = popped_slice; - last_elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) { - self.slice = self.slice.insert(index, elem); -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T { - let (new_slice, elem) = self.slice.remove(index); - self.slice = new_slice; - elem -} -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field { - self.slice.len() -} -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/functions.md deleted file mode 100644 index 48aba9cd058..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/oracles.md deleted file mode 100644 index 2e6a6818d48..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/oracles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/unconstrained.md deleted file mode 100644 index 89d12c1c971..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index d9d21ef0485..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 48d2408e1e4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.24.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.24.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4bf09cef178..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index a9c10da6c06..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 730b6d4117f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,234 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L5-L7 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L11-L13 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L17-L19 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L42-L44 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint -``` -> Source code: noir_stdlib/src/hash.nr#L22-L29 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L67-L69 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L11 - - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index ae12e6c12dc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index fa488677884..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/recursion.md deleted file mode 100644 index ed2ed01fceb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/traits.md deleted file mode 100644 index ba9fa2ee841..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/traits.md +++ /dev/null @@ -1,399 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(input: Self) -> T; -} - -impl Into for U where T: From { - fn into(input: U) -> T { - T::from(input) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L92-L96 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/nargo_commands.md deleted file mode 100644 index 8a309ef4e7e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/reference/nargo_commands.md +++ /dev/null @@ -1,380 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on a circuit -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on a circuit - -Current information provided: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.24.0/tutorials/noirjs_app.md deleted file mode 100644 index 0d75e2e8045..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.24.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.19.x matches `noir_js@0.19.x`, etc. - -In this guide, we will be pinned to 0.19.4. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to *anyone* is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -```nargo new circuit``` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -```nargo compile``` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -You should see `vite-project` appear in your root folder. This seems like a good time to `cd` into it and install our NoirJS packages: - -```bash -npm i @noir-lang/backend_barretenberg@0.19.4 @noir-lang/noir_js@0.19.4 -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It *could* be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import("@noir-lang/noirc_abi").then(module => - module.default(new URL("@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm", import.meta.url).toString()) - ), - import("@noir-lang/acvm_js").then(module => - module.default(new URL("@noir-lang/acvm_js/web/acvm_js_bg.wasm", import.meta.url).toString()) - ) - ]); -} - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch(err) { - display("logs", "Oh 💔 Wrong guess") - } -}); - -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index a35e34aaf9c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,254 +0,0 @@ ---- -title: Alternative Install Methods -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains other methods that don't rely on noirup, such as compiling from source, installing from binaries, and using WSL for windows -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Shell & editor experience - Building and testing - Uninstalling Nargo - Noir vs code extension, - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Alternate Installation Methods (No Longer Recommended) - -While the following methods are available, they are no longer recommended. We advise using noirup for a more efficient and flexible installation experience. - -However, there are other methods for installing Nargo: - -- [Binaries](#option-1-installing-from-binaries) -- [Compiling from Source](#option-2-compile-from-source) -- [WSL for Windows](#option-3-wsl-for-windows) - -### Option 1: Installing from Binaries - -See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous -platform specific binaries. - -#### Step 1 - -Paste and run the following in the terminal to extract and install the binary: - -> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend -> `sudo` and re-run it. - -##### macOS (Apple Silicon) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-aarch64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### macOS (Intel) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-x86_64-apple-darwin.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ -echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ -source ~/.zshrc -``` - -##### Linux (Bash) - -```bash -mkdir -p $HOME/.nargo/bin && \ -curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.24.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ -tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ -echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ -source ~/.bashrc -``` - -#### Step 2 - -Check if the installation was successful by running `nargo --version`. You should get a version number. - -> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from -> Finder. Close the new terminal popped up and `nargo` should now be accessible. - -### Option 2: Compile from Source - -Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating issues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). - -Combined with direnv, which automatically sets or clears environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. - -#### Setting up your environment - -For the best experience, please follow these instructions to setup your environment: - -1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. -2. Create the file `~/.config/nix/nix.conf` with the contents: - -```ini -experimental-features = nix-command -extra-experimental-features = flakes -``` - -3. Install direnv into your Nix profile by running: - -```sh -nix profile install nixpkgs#direnv -``` - -4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). - 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. -5. Restart your shell. - -#### Shell & editor experience - -Now that your environment is set up, you can get to work on the project. - -1. Clone the repository, such as: - -```sh -git clone git@github.com:noir-lang/noir -``` - -> Replacing `noir` with whichever repository you want to work on. - -2. Navigate to the directory: - -```sh -cd noir -``` - -> Replacing `noir` with whichever repository you cloned. - -3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: - -```sh -direnv allow -``` - -4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. - -5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): - -```sh -code . -``` - -6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. - -#### Building and testing - -Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.73.0 at the time of this writing. - -If you want to build the entire project in an isolated sandbox, you can use Nix commands: - -1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. -2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. - -#### Without `direnv` - -If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. - -Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! - -### Option 3: WSL (for Windows) - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -### Noirup - -If you installed Nargo with `noirup` or through directly downloading binaries, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` - -### Nix - -If you installed Nargo with Nix or compiled it from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. - -```bash -rm ~/.nix-profile/bin/nargo -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/_category_.json deleted file mode 100644 index 55804c03a71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 2, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/index.mdx deleted file mode 100644 index ec9ccea4115..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - - - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-oracles.md deleted file mode 100644 index ab225b9421f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,280 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map(({ inner }) => { - return { inner: `${Math.sqrt(parseInt(inner, 16))}` }; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a `inner` property *as a string*. For example: - -```json -{ "values": [{ "Array": [{ "inner": "1" }, { "inner": "2"}]}]} -{ "values": [{ "Single": { "inner": "1" }}]} -{ "values": [{ "Single": { "inner": "1" }}, { "Array": [{ "inner": "1", { "inner": "2" }}]}]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface Value { - inner: string, -} - -interface SingleForeignCallParam { - Single: Value, -} - -interface ArrayForeignCallParam { - Array: Value[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => ({ inner: i.toString("hex") })) }, - ]); - return [oracleReturn.values[0].Array.map((x) => x.inner)]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/merkle-proof.mdx deleted file mode 100644 index 34074659ac1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/control_flow.md deleted file mode 100644 index 4ce65236db3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -}; -``` - -The index for loops is of type `u64`. - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9a4c485feb1..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = []; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/fields.md deleted file mode 100644 index 99b4aa63549..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 4d58d96fed5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports both unsigned and signed integer types. The allowed sizes are 1, 8, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4a6ee816aa2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = [0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = []; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = [1, 2].append([3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/functions.md deleted file mode 100644 index 48aba9cd058..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main([1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/oracles.md deleted file mode 100644 index 2e6a6818d48..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/oracles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/unconstrained.md deleted file mode 100644 index 89d12c1c971..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,95 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index ce4529f6e57..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 91604af765d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,569 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a pedersen hash -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index 1954f05bc76..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let arr: [Field] = [1, 2, 3]; -let vector_from_slice = Vec::from_slice(arr); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice([10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice([10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 694b385e5ae..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.25.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.25.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4bf09cef178..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,60 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 119d8ccc70e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L9-L11 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L15-L17 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L21-L23 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L46-L48 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint -``` -> Source code: noir_stdlib/src/hash.nr#L26-L33 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes -(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes -of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L71-L73 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field; N]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index ae12e6c12dc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index fa488677884..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/recursion.md deleted file mode 100644 index ed2ed01fceb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(verify_proof)] -fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/traits.md deleted file mode 100644 index ba9fa2ee841..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/traits.md +++ /dev/null @@ -1,399 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(input: Self) -> T; -} - -impl Into for U where T: From { - fn into(input: U) -> T { - T::from(input) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L92-L96 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/zeroed.md deleted file mode 100644 index 97dab02dac2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index d60940df3ea..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,127 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../interfaces/Backend.md) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Implementation of - -[`Backend`](../interfaces/Backend.md).[`destroy`](../interfaces/Backend.md#destroy) - -#### Description - -Destroys the backend - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index e32501acb71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,46 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Interfaces - -| Interface | Description | -| :------ | :------ | -| [Backend](interfaces/Backend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): WitnessMap -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -`WitnessMap` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md deleted file mode 100644 index 3eb9645c8d2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/interfaces/Backend.md +++ /dev/null @@ -1,132 +0,0 @@ -# Backend - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the backend - -*** - -### generateFinalProof() - -```ts -generateFinalProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a final proof (not meant to be verified in another circuit) - -*** - -### generateIntermediateProof() - -```ts -generateIntermediateProof(decompressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `decompressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates an intermediate proof (meant to be verified in another circuit) - -*** - -### generateIntermediateProofArtifacts() - -```ts -generateIntermediateProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | -| `numOfPublicInputs` | `number` | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Retrieves the artifacts from a proof in the Field format - -*** - -### verifyFinalProof() - -```ts -verifyFinalProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a final proof - -*** - -### verifyIntermediateProof() - -```ts -verifyIntermediateProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies an intermediate proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md deleted file mode 100644 index 05cebbc4e94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `string`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 2aaa55bccf6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Interfaces","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/interfaces/Backend","label":"Backend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/ProofData","label":"ProofData"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 421d274fff8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | [`CompiledCircuit`](../type-aliases/CompiledCircuit.md) | -| `backend`? | `Backend` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | [`InputMap`](../type-aliases/InputMap.md) | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<[`ProofData`](../type-aliases/ProofData.md)\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | [`ProofData`](../type-aliases/ProofData.md) | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index d600e21b299..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,37 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [CompiledCircuit](type-aliases/CompiledCircuit.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [InputMap](type-aliases/InputMap.md) | - | -| [ProofData](type-aliases/ProofData.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md deleted file mode 100644 index 34e0dd04205..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/CompiledCircuit.md +++ /dev/null @@ -1,20 +0,0 @@ -# CompiledCircuit - -```ts -type CompiledCircuit: object; -``` - -## Description - -The representation of a compiled circuit - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `abi` | `Abi` | **Description**

ABI representation of the circuit | -| `bytecode` | `string` | **Description**

The bytecode of the circuit | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/InputMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/InputMap.md deleted file mode 100644 index c714e999d93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/InputMap.md +++ /dev/null @@ -1,13 +0,0 @@ -# InputMap - -```ts -type InputMap: object; -``` - -## Index signature - - \[`key`: `string`\]: `InputValue` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ProofData.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ProofData.md deleted file mode 100644 index 05cebbc4e94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/ProofData.md +++ /dev/null @@ -1,20 +0,0 @@ -# ProofData - -```ts -type ProofData: object; -``` - -## Description - -The representation of a proof - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `proof` | `Uint8Array` | **Description**

An byte array representing the proof | -| `publicInputs` | `string`[] | **Description**

Public inputs of a proof | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index fe2629ddc9f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/CompiledCircuit","label":"CompiledCircuit"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/InputMap","label":"InputMap"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ProofData","label":"ProofData"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/nargo_commands.md deleted file mode 100644 index 8a309ef4e7e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/reference/nargo_commands.md +++ /dev/null @@ -1,380 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on a circuit -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on a circuit - -Current information provided: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.25.0/tutorials/noirjs_app.md deleted file mode 100644 index 0cea72314ce..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.25.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,324 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.25.x matches `noir_js@0.25.x`, etc. - -In this guide, we will be pinned to 0.25.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -`nargo new circuit` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -`nargo compile` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from "vite"; -import copy from "rollup-plugin-copy"; - -export default defineConfig({ - esbuild: { - target: "esnext", - }, - optimizeDeps: { - esbuildOptions: { - target: "esnext", - }, - }, - plugins: [ - copy({ - targets: [ - { src: "node_modules/**/*.wasm", dest: "node_modules/.vite/dist" }, - ], - copySync: true, - hook: "buildStart", - }), - ], - server: { - port: 3000, - }, -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.25.0 @noir-lang/noir_js@0.25.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import('@noir-lang/noirc_abi').then((module) => - module.default(new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString()), - ), - import('@noir-lang/acvm_js').then((module) => - module.default(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()), - ), - ]); -}; - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - └── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/_category_.json deleted file mode 100644 index 55804c03a71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 2, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/index.mdx deleted file mode 100644 index ec9ccea4115..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - - - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index d65151da0ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 2 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = {"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"param_witnesses":{"x":[{"start":0,"end":1}],"y":[{"start":1,"end":2}]},"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"},"return_witnesses":[4]},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-oracles.md deleted file mode 100644 index 8cf8035a5c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a field element *as a string*. For example: - -```json -{ "values": [{ "Array": ["1", "2"] }]} -{ "values": [{ "Single": "1" }]} -{ "values": [{ "Single": "1" }, { "Array": ["1", "2"] }]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/merkle-proof.mdx deleted file mode 100644 index 003c7019a93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 1c6b375db49..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports both unsigned and signed integer types. The allowed sizes are 1, 8, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 828faf4a8f8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/functions.md deleted file mode 100644 index 2c9bc33fdfc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/oracles.md deleted file mode 100644 index 2e6a6818d48..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/oracles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bigint.md deleted file mode 100644 index da6a7cdfd81..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L16-L21 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L20-L28 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index ce4529f6e57..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 91604af765d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,569 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a pedersen hash -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index fcfd7e07aa0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index aa679fa1086..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.26.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.26.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 695c7d9406f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. -See sha256_slice for a version that works directly on slices. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L10-L12 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## sha256_slice - -A version of sha256 specialized to slices: - -```rust title="sha256_slice" showLineNumbers -pub fn sha256_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L16-L18 - - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash -See blake2s_slice for a version that works directly on slices. - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L22-L24 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake2s_slice - -A version of blake2s specialized to slices: - -```rust title="blake2s_slice" showLineNumbers -pub fn blake2s_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L28-L30 - - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash -See blake3_slice for a version that works directly on slices. - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L34-L36 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## blake3_slice - -A version of blake3 specialized to slices: - -```rust title="blake3_slice" showLineNumbers -pub fn blake3_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L40-L42 - - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. -See pedersen_hash_slice for a version that works directly on slices. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L78-L80 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - -## pedersen_hash_slice - -Given a slice of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash_slice" showLineNumbers -pub fn pedersen_hash_slice(input: [Field]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L85-L87 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. -See pedersen_commitment_slice for a version that works directly on slices. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint { -``` -> Source code: noir_stdlib/src/hash.nr#L45-L52 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## pedersen_commitment_slice - -Given a slice of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment_slice" showLineNumbers -pub fn pedersen_commitment_slice(input: [Field]) -> PedersenPoint { - pedersen_commitment_with_separator_slice(input, 0) -} -``` -> Source code: noir_stdlib/src/hash.nr#L56-L60 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. See keccak256_slice for a version that works -directly on slices. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L113-L115 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## keccak256_slice - -Given a slice of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). - -```rust title="keccak256_slice" showLineNumbers -pub fn keccak256_slice(input: [u8], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L119-L121 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/recursion.md deleted file mode 100644 index f33c285cf4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/traits.md deleted file mode 100644 index 68a9dc3d54b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/traits.md +++ /dev/null @@ -1,408 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(input: Self) -> T; -} - -impl Into for U where T: From { - fn into(input: U) -> T { - T::from(input) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index b18c1926b93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,119 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index c146316a915..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,58 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): Backend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -[`Backend`](index.md#backend) - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 339353b9862..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 45dd62ee57e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | -| `backend`? | `any` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index cca6b3ace41..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -*** - -### ProofData - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c6d8125eaad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/nargo_commands.md deleted file mode 100644 index 218fcfb0c8c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/reference/nargo_commands.md +++ /dev/null @@ -1,381 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.26.0/tutorials/noirjs_app.md deleted file mode 100644 index a6dda7e08c3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.26.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,324 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.26.x matches `noir_js@0.26.x`, etc. - -In this guide, we will be pinned to 0.26.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -`nargo new circuit` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -`nargo compile` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from "vite"; -import copy from "rollup-plugin-copy"; - -export default defineConfig({ - esbuild: { - target: "esnext", - }, - optimizeDeps: { - esbuildOptions: { - target: "esnext", - }, - }, - plugins: [ - copy({ - targets: [ - { src: "node_modules/**/*.wasm", dest: "node_modules/.vite/dist" }, - ], - copySync: true, - hook: "buildStart", - }), - ], - server: { - port: 3000, - }, -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.26.0 @noir-lang/noir_js@0.26.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import('@noir-lang/noirc_abi').then((module) => - module.default(new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString()), - ), - import('@noir-lang/acvm_js').then((module) => - module.default(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()), - ), - ]); -}; - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - └── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/_category_.json deleted file mode 100644 index 55804c03a71..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 2, - "label": "Tooling", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/index.mdx deleted file mode 100644 index ec9ccea4115..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/index.mdx +++ /dev/null @@ -1,34 +0,0 @@ ---- -title: Tooling -Description: This section provides information about the various tools and utilities available for Noir development. It covers IDE tools, Codespaces, and community projects. -Keywords: [Noir, Development, Playground, IDE Tools, Language Service Provider, VS Code Extension, Codespaces, noir-starter, Community Projects, Awesome Noir Repository, Developer Tooling] ---- - -Noir is meant to be easy to develop with. For that reason, a number of utilities have been put together to ease the development process as much as feasible in the zero-knowledge world. - -## IDE tools - -When you install Nargo, you're also installing a Language Service Provider (LSP), which can be used by IDEs to provide syntax highlighting, codelens, warnings, and more. - -The easiest way to use these tools is by installing the [Noir VS Code extension](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -## Codespaces - -Some Noir repos have leveraged Codespaces in order to ease the development process. You can visit the [noir-starter](https://github.com/noir-lang/noir-starter) for an example. - - - -## GitHub Actions - -You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as -installing `noirup` and running tests in your GitHub Action `yml` file. - -See the -[config file in the Noir repo](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) for an example usage. - -## Community projects - -As an open-source project, Noir has received many contributions over time. Some of them are related with developer tooling, and you can see some of them in [Awesome Noir repository](https://github.com/noir-lang/awesome-noir#dev-tools) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index d65151da0ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 2 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = {"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"param_witnesses":{"x":[{"start":0,"end":1}],"y":[{"start":1,"end":2}]},"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"},"return_witnesses":[4]},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/getting_started/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-oracles.md deleted file mode 100644 index 8cf8035a5c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a field element *as a string*. For example: - -```json -{ "values": [{ "Array": ["1", "2"] }]} -{ "values": [{ "Single": "1" }]} -{ "values": [{ "Single": "1" }, { "Array": ["1", "2"] }]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/merkle-proof.mdx deleted file mode 100644 index 003c7019a93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 1c6b375db49..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports both unsigned and signed integer types. The allowed sizes are 1, 8, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 828faf4a8f8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/functions.md deleted file mode 100644 index 2c9bc33fdfc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../getting_started/tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../getting_started/tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/oracles.md deleted file mode 100644 index 2e6a6818d48..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/oracles.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bigint.md deleted file mode 100644 index da6a7cdfd81..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,119 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L16-L21 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L20-L28 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index ce4529f6e57..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 91604af765d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,569 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a pedersen hash -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index fcfd7e07aa0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 042347cb98f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.27.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.27.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 695c7d9406f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,331 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. -See sha256_slice for a version that works directly on slices. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L10-L12 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## sha256_slice - -A version of sha256 specialized to slices: - -```rust title="sha256_slice" showLineNumbers -pub fn sha256_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L16-L18 - - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash -See blake2s_slice for a version that works directly on slices. - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L22-L24 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake2s_slice - -A version of blake2s specialized to slices: - -```rust title="blake2s_slice" showLineNumbers -pub fn blake2s_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L28-L30 - - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash -See blake3_slice for a version that works directly on slices. - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L34-L36 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## blake3_slice - -A version of blake3 specialized to slices: - -```rust title="blake3_slice" showLineNumbers -pub fn blake3_slice(input: [u8]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L40-L42 - - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. -See pedersen_hash_slice for a version that works directly on slices. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L78-L80 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - -## pedersen_hash_slice - -Given a slice of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash_slice" showLineNumbers -pub fn pedersen_hash_slice(input: [Field]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L85-L87 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. -See pedersen_commitment_slice for a version that works directly on slices. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint { -``` -> Source code: noir_stdlib/src/hash.nr#L45-L52 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## pedersen_commitment_slice - -Given a slice of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment_slice" showLineNumbers -pub fn pedersen_commitment_slice(input: [Field]) -> PedersenPoint { - pedersen_commitment_with_separator_slice(input, 0) -} -``` -> Source code: noir_stdlib/src/hash.nr#L56-L60 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. See keccak256_slice for a version that works -directly on slices. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L113-L115 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## keccak256_slice - -Given a slice of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). - -```rust title="keccak256_slice" showLineNumbers -pub fn keccak256_slice(input: [u8], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L119-L121 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/recursion.md deleted file mode 100644 index f33c285cf4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/traits.md deleted file mode 100644 index 68a9dc3d54b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/traits.md +++ /dev/null @@ -1,408 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(input: Self) -> T; -} - -impl Into for U where T: From { - fn into(input: U) -> T { - T::from(input) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index b18c1926b93..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,119 +0,0 @@ -# BarretenbergBackend - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index c146316a915..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,58 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): Backend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -[`Backend`](index.md#backend) - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index 339353b9862..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 45dd62ee57e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | -| `backend`? | `any` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index cca6b3ace41..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -*** - -### ProofData - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c6d8125eaad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/nargo_commands.md deleted file mode 100644 index 218fcfb0c8c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/reference/nargo_commands.md +++ /dev/null @@ -1,381 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.27.0/tutorials/noirjs_app.md deleted file mode 100644 index 0d75e2e8045..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.27.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,279 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.19.x matches `noir_js@0.19.x`, etc. - -In this guide, we will be pinned to 0.19.4. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to *anyone* is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -```nargo new circuit``` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -```nargo compile``` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -You should see `vite-project` appear in your root folder. This seems like a good time to `cd` into it and install our NoirJS packages: - -```bash -npm i @noir-lang/backend_barretenberg@0.19.4 @noir-lang/noir_js@0.19.4 -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It *could* be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import("@noir-lang/noirc_abi").then(module => - module.default(new URL("@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm", import.meta.url).toString()) - ), - import("@noir-lang/acvm_js").then(module => - module.default(new URL("@noir-lang/acvm_js/web/acvm_js_bg.wasm", import.meta.url).toString()) - ) - ]); -} - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch(err) { - display("logs", "Oh 💔 Wrong guess") - } -}); - -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verification = await noir.verifyProof(proof); -if (verification) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index d65151da0ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 2 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = {"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"param_witnesses":{"x":[{"start":0,"end":1}],"y":[{"start":1,"end":2}]},"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"},"return_witnesses":[4]},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/_category_.json deleted file mode 100644 index cc2cbb1c253..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugging", - "position": 5, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_the_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_the_repl.md deleted file mode 100644 index 09e5bae68ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_the_repl.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Using the REPL Debugger -description: - Step by step guide on how to debug your Noir circuits with the REPL Debugger. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -#### Pre-requisites - -In order to use the REPL debugger, first you need to install recent enough versions of Nargo and vscode-noir. - -## Debugging a simple circuit - -Let's debug a simple circuit: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -To start the REPL debugger, using a terminal, go to a Noir circuit's home directory. Then: - -`$ nargo debug` - -You should be seeing this in your terminal: - -``` -[main] Starting debugger -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:9 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> -``` - -The debugger displays the current Noir code location, and it is now waiting for us to drive it. - -Let's first take a look at the available commands. For that we'll use the `help` command. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -Some commands operate only for unconstrained functions, such as `memory` and `memset`. If you try to use them while execution is paused at an ACIR opcode, the debugger will simply inform you that you are not executing unconstrained code: - -``` -> memory -Unconstrained VM memory not available -> -``` - -Before continuing, we can take a look at the initial witness map: - -``` -> witness -_0 = 1 -_1 = 2 -> -``` - -Cool, since `x==1`, `y==2`, and we want to check that `x != y`, our circuit should succeed. At this point we could intervene and use the witness setter command to change one of the witnesses. Let's set `y=3`, then back to 2, so we don't affect the expected result: - -``` -> witness -_0 = 1 -_1 = 2 -> witness 1 3 -_1 = 3 -> witness -_0 = 1 -_1 = 3 -> witness 1 2 -_1 = 2 -> witness -_0 = 1 -_1 = 2 -> -``` - -Now we can inspect the current state of local variables. For that we use the `vars` command. - -``` -> vars -> -``` - -We currently have no vars in context, since we are at the entry point of the program. Let's use `next` to execute until the next point in the program. - -``` -> vars -> next -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:20 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> vars -x:Field = 0x01 -``` - -As a result of stepping, the variable `x`, whose initial value comes from the witness map, is now in context and returned by `vars`. - -``` -> next - 1 fn main(x : Field, y : pub Field) { - 2 -> assert(x != y); - 3 } -> vars -y:Field = 0x02 -x:Field = 0x01 -``` - -Stepping again we can finally see both variables and their values. And now we can see that the next assertion should succeed. - -Let's continue to the end: - -``` -> continue -(Continuing execution...) -Finished execution -> q -[main] Circuit witness successfully solved -``` - -Upon quitting the debugger after a solved circuit, the resulting circuit witness gets saved, equivalent to what would happen if we had run the same circuit with `nargo execute`. - -We just went through the basics of debugging using Noir REPL debugger. For a comprehensive reference, check out [the reference page](../../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_vs_code.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_vs_code.md deleted file mode 100644 index a5858c1a5eb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/debugger/debugging_with_vs_code.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Using the VS Code Debugger -description: - Step by step guide on how to debug your Noir circuits with the VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -This guide will show you how to use VS Code with the vscode-noir extension to debug a Noir project. - -#### Pre-requisites - -- Nargo -- vscode-noir -- A Noir project with a `Nargo.toml`, `Prover.toml` and at least one Noir (`.nr`) containing an entry point function (typically `main`). - -## Running the debugger - -The easiest way to start debugging is to open the file you want to debug, and press `F5`. This will cause the debugger to launch, using your `Prover.toml` file as input. - -You should see something like this: - -![Debugger launched](@site/static/img/debugger/1-started.png) - -Let's inspect the state of the program. For that, we open VS Code's _Debug pane_. Look for this icon: - -![Debug pane icon](@site/static/img/debugger/2-icon.png) - -You will now see two categories of variables: Locals and Witness Map. - -![Debug pane expanded](@site/static/img/debugger/3-debug-pane.png) - -1. **Locals**: variables of your program. At this point in execution this section is empty, but as we step through the code it will get populated by `x`, `result`, `digest`, etc. - -2. **Witness map**: these are initially populated from your project's `Prover.toml` file. In this example, they will be used to populate `x` and `result` at the beginning of the `main` function. - -Most of the time you will probably be focusing mostly on locals, as they represent the high level state of your program. - -You might be interested in inspecting the witness map in case you are trying to solve a really low level issue in the compiler or runtime itself, so this concerns mostly advanced or niche users. - -Let's step through the program, by using the debugger buttons or their corresponding keyboard shortcuts. - -![Debugger buttons](@site/static/img/debugger/4-debugger-buttons.png) - -Now we can see in the variables pane that there's values for `digest`, `result` and `x`. - -![Inspecting locals](@site/static/img/debugger/5-assert.png) - -We can also inspect the values of variables by directly hovering on them on the code. - -![Hover locals](@site/static/img/debugger/6-hover.png) - -Let's set a break point at the `keccak256` function, so we can continue execution up to the point when it's first invoked without having to go one step at a time. - -We just need to click the to the right of the line number 18. Once the breakpoint appears, we can click the `continue` button or use its corresponding keyboard shortcut (`F5` by default). - -![Breakpoint](@site/static/img/debugger/7-break.png) - -Now we are debugging the `keccak256` function, notice the _Call Stack pane_ at the lower right. This lets us inspect the current call stack of our process. - -That covers most of the current debugger functionalities. Check out [the reference](../../reference/debugger/debugger_vscode.md) for more details on how to configure the debugger. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-oracles.md deleted file mode 100644 index 8cf8035a5c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a field element *as a string*. For example: - -```json -{ "values": [{ "Array": ["1", "2"] }]} -{ "values": [{ "Single": "1" }]} -{ "values": [{ "Single": "1" }, { "Array": ["1", "2"] }]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/merkle-proof.mdx deleted file mode 100644 index 16c425bed76..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] -sidebar_position: 4 ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 1c6b375db49..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports both unsigned and signed integer types. The allowed sizes are 1, 8, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4eccc677b80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` - -### as_array - -Converts this slice into an array. - -Make sure to specify the size of the resulting array. -Panics if the resulting array length is different than the slice's length. - -```rust -fn as_array(self) -> [T; N] -``` - -Example: - -```rust -fn main() { - let slice = &[5, 6]; - - // Always specify the length of the resulting array! - let array: [Field; 2] = slice.as_array(); - - assert(array[0] == slice[0]); - assert(array[1] == slice[1]); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/distinct.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/distinct.md deleted file mode 100644 index 6c993b8b5e0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/distinct.md +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Distinct Witnesses -sidebar_position: 11 ---- - -The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures -that the witnesses being returned as public inputs are all unique. - -The `distinct` keyword is only used for return values on program entry points (usually the `main()` -function). - -When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. - -You can read more about the problem this solves -[here](https://github.com/noir-lang/noir/issues/1183). - -## Example - -Without the `distinct` keyword, the following program - -```rust -fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - "return_witnesses": [3, 2, 4, 4] - } -} -``` - -Whereas (with the `distinct` keyword) - -```rust -fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { - let a = 1; - let b = 1; - [x + 1, y, a, b] -} -``` - -compiles to - -```json -{ - //... - "abi": { - //... - "param_witnesses": { "x": [1], "y": [2] }, - //... - "return_witnesses": [3, 4, 5, 6] - } -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/functions.md deleted file mode 100644 index f656cdfd97a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/ops.md deleted file mode 100644 index 60425cb8994..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer | -| >> | Right shift an integer by another integer amount | Types must be integer | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/oracles.md deleted file mode 100644 index aa380b5f7b8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/oracles.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -:::note - -This is an experimental feature that is not fully documented. If you notice any outdated information or potential improvements to this page, pull request contributions are very welcome: https://github.com/noir-lang/noir - -::: - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` - -The timeout for when using an external RPC oracle resolver can be set with the `NARGO_FOREIGN_CALL_TIMEOUT` environment variable. This timeout is in units of milliseconds. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bigint.md deleted file mode 100644 index 2bfdeec6631..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L14-L19 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L70-L78 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - // Construct a big integer from a slice of bytes - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - // Construct a big integer from an array of 32 bytes - let a = Secpk1Fq::from_le_bytes_32([1;32]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index ce4529f6e57..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 47faa99aba6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,570 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a poseidon2 hasher -use dep::std::hash::poseidon2::Poseidon2Hasher; -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index fcfd7e07aa0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 9c6987b693e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.28.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.28.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 87e113b96cd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,250 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L9-L11 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::sha256(x); -} -``` - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L15-L17 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L21-L23 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L45-L47 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint { -``` -> Source code: noir_stdlib/src/hash.nr#L26-L33 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L67-L69 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/recursion.md deleted file mode 100644 index f33c285cf4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/traits.md deleted file mode 100644 index 94337e77a3e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/traits.md +++ /dev/null @@ -1,410 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(self) -> T; -} - -impl Into for U where T: From { - fn into(self) -> T { - T::from(self) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -`std::cmp` also provides `max` and `min` functions for any type which implements the `Ord` trait. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index d7249d24330..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,160 +0,0 @@ -# BarretenbergBackend - -## Extends - -- `BarretenbergVerifierBackend` - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -#### Inherited from - -BarretenbergVerifierBackend.constructor - -## Properties - -| Property | Type | Description | Inheritance | -| :------ | :------ | :------ | :------ | -| `acirComposer` | `any` | - | BarretenbergVerifierBackend.acirComposer | -| `acirUncompressedBytecode` | `Uint8Array` | - | BarretenbergVerifierBackend.acirUncompressedBytecode | -| `api` | `Barretenberg` | - | BarretenbergVerifierBackend.api | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - | BarretenbergVerifierBackend.options | - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Inherited from - -BarretenbergVerifierBackend.destroy - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### getVerificationKey() - -```ts -getVerificationKey(): Promise -``` - -#### Returns - -`Promise`\<`Uint8Array`\> - -#### Inherited from - -BarretenbergVerifierBackend.getVerificationKey - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Inherited from - -BarretenbergVerifierBackend.verifyProof - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md deleted file mode 100644 index 500276ea748..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md +++ /dev/null @@ -1,58 +0,0 @@ -# BarretenbergVerifier - -## Constructors - -### new BarretenbergVerifier(options) - -```ts -new BarretenbergVerifier(options): BarretenbergVerifier -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergVerifier`](BarretenbergVerifier.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### verifyProof() - -```ts -verifyProof(proofData, verificationKey): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | -| `verificationKey` | `Uint8Array` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index 64971973196..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | -| [BarretenbergVerifier](classes/BarretenbergVerifier.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): Backend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -[`Backend`](index.md#backend) - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index d7d5128f9e3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier","label":"BarretenbergVerifier"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 45dd62ee57e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | -| `backend`? | `any` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index cca6b3ace41..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -*** - -### ProofData - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c6d8125eaad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/_category_.json deleted file mode 100644 index 27869205ad3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugger", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_known_limitations.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_known_limitations.md deleted file mode 100644 index 936d416ac4b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_known_limitations.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Known limitations -description: - An overview of known limitations of the current version of the Noir debugger -keywords: - [ - Nargo, - Noir Debugger, - VS Code, - ] -sidebar_position: 2 ---- - -# Debugger Known Limitations - -There are currently some limits to what the debugger can observe. - -## Mutable references - -The debugger is currently blind to any state mutated via a mutable reference. For example, in: - -``` -let mut x = 1; -let y = &mut x; -*y = 2; -``` - -The update on `x` will not be observed by the debugger. That means, when running `vars` from the debugger REPL, or inspecting the _local variables_ pane in the VS Code debugger, `x` will appear with value 1 despite having executed `*y = 2;`. - -## Variables of type function or mutable references are opaque - -When inspecting variables, any variable of type `Function` or `MutableReference` will render its value as `<>` or `<>`. - -## Debugger instrumentation affects resulting ACIR - -In order to make the state of local variables observable, the debugger compiles Noir circuits interleaving foreign calls that track any mutations to them. While this works (except in the cases described above) and doesn't introduce any behavior changes, it does as a side effect produce bigger bytecode. In particular, when running the command `opcodes` on the REPL debugger, you will notice Unconstrained VM blocks that look like this: - -``` -... -5 BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [], q_c: 2 }), Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(2))], q_c: 0 })] - | outputs=[] - 5.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 5.1 | Mov { destination: RegisterIndex(3), source: RegisterIndex(1) } - 5.2 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 5.3 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 5.4 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 5.5 | Mov { destination: RegisterIndex(3), source: RegisterIndex(3) } - 5.6 | Call { location: 8 } - 5.7 | Stop - 5.8 | ForeignCall { function: "__debug_var_assign", destinations: [], inputs: [RegisterIndex(RegisterIndex(2)), RegisterIndex(RegisterIndex(3))] } -... -``` - -If you are interested in debugging/inspecting compiled ACIR without these synthetic changes, you can invoke the REPL debugger with the `--skip-instrumentation` flag or launch the VS Code debugger with the `skipConfiguration` property set to true in its launch configuration. You can find more details about those in the [Debugger REPL reference](debugger_repl.md) and the [VS Code Debugger reference](debugger_vscode.md). - -:::note -Skipping debugger instrumentation means you won't be able to inspect values of local variables. -::: - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_repl.md deleted file mode 100644 index 46e2011304e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_repl.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: REPL Debugger -description: - Noir Debugger REPL options and commands. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -## Running the REPL debugger - -`nargo debug [OPTIONS] [WITNESS_NAME]` - -Runs the Noir REPL debugger. If a `WITNESS_NAME` is provided the debugger writes the resulting execution witness to a `WITNESS_NAME` file. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover]| -| `--package ` | The name of the package to debug | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -None of these options are required. - -:::note -Since the debugger starts by compiling the target package, all Noir compiler options are also available. Check out the [compiler reference](../nargo_commands.md#nargo-compile) to learn more about the compiler options. -::: - -## REPL commands - -Once the debugger is running, it accepts the following commands. - -#### `help` (h) - -Displays the menu of available commands. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) value - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -### Stepping through programs - -#### `next` (n) - -Step until the next Noir source code location. While other commands, such as [`into`](#into-i) and [`step`](#step-s), allow for finer grained control of the program's execution at the opcode level, `next` is source code centric. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `next` here would cause the debugger to jump to the definition of `deep_entry_point` (if available). - -If you want to step over `deep_entry_point` and go straight to line 8, use [the `over` command](#over) instead. - -#### `over` - -Step until the next source code location, without diving into function calls. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `over` here would cause the debugger to execute until line 8 (`multiple_values_entry_point(x);`). - -If you want to step into `deep_entry_point` instead, use [the `next` command](#next-n). - -#### `out` - -Step until the end of the current function call. For example: - -``` - 3 ... - 4 fn main(x: u32) { - 5 assert(entry_point(x) == 2); - 6 swap_entry_point(x, x + 1); - 7 -> assert(deep_entry_point(x) == 4); - 8 multiple_values_entry_point(x); - 9 } - 10 - 11 unconstrained fn returns_multiple_values(x: u32) -> (u32, u32, u32, u32) { - 12 ... - ... - 55 - 56 unconstrained fn deep_entry_point(x: u32) -> u32 { - 57 -> level_1(x + 1) - 58 } - -``` - -Running `out` here will resume execution until line 8. - -#### `step` (s) - -Skips to the next ACIR code. A compiled Noir program is a sequence of ACIR opcodes. However, an unconstrained VM opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `step` command at this point would result in the debugger stopping at ACIR opcode 2, `EXPR`, skipping unconstrained computation steps. - -Use [the `into` command](#into-i) instead if you want to follow unconstrained computation step by step. - -#### `into` (i) - -Steps into the next opcode. A compiled Noir program is a sequence of ACIR opcodes. However, a BRILLIG opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `into` command at this point would result in the debugger stopping at opcode 1.0, `Mov ...`, allowing the debugger user to follow unconstrained computation step by step. - -Use [the `step` command](#step-s) instead if you want to skip to the next ACIR code directly. - -#### `continue` (c) - -Continues execution until the next breakpoint, or the end of the program. - -#### `restart` (res) - -Interrupts execution, and restarts a new debugging session from scratch. - -#### `opcodes` (o) - -Display the program's ACIR opcode sequence. For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -### Breakpoints - -#### `break [Opcode]` (or shorthand `b [Opcode]`) - -Sets a breakpoint on the specified opcode index. To get a list of the program opcode numbers, see [the `opcode` command](#opcodes-o). For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -In this example, issuing a `break 1.2` command adds break on opcode 1.2, as denoted by the `*` character: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | * Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -Running [the `continue` command](#continue-c) at this point would cause the debugger to execute the program until opcode 1.2. - -#### `delete [Opcode]` (or shorthand `d [Opcode]`) - -Deletes a breakpoint at an opcode location. Usage is analogous to [the `break` command](#). - -### Variable inspection - -#### vars - -Show variable values available at this point in execution. - -:::note -The ability to inspect variable values from the debugger depends on compilation to be run in a special debug instrumentation mode. This instrumentation weaves variable tracing code with the original source code. - -So variable value inspection comes at the expense of making the resulting ACIR bytecode bigger and harder to understand and optimize. - -If you find this compromise unacceptable, you can run the debugger with the flag `--skip-debug-instrumentation`. This will compile your circuit without any additional debug information, so the resulting ACIR bytecode will be identical to the one produced by standard Noir compilation. However, if you opt for this, the `vars` command will not be available while debugging. -::: - - -### Stacktrace - -#### `stacktrace` - -Displays the current stack trace. - - -### Witness map - -#### `witness` (w) - -Show witness map. For example: - -``` -_0 = 0 -_1 = 2 -_2 = 1 -``` - -#### `witness [Witness Index]` - -Display a single witness from the witness map. For example: - -``` -> witness 1 -_1 = 2 -``` - -#### `witness [Witness Index] [New value]` - -Overwrite the given index with a new value. For example: - -``` -> witness 1 3 -_1 = 3 -``` - - -### Unconstrained VM memory - -#### `memory` - -Show unconstrained VM memory state. For example: - -``` -> memory -At opcode 1.13: Store { destination_pointer: RegisterIndex(0), source: RegisterIndex(3) } -... -> registers -0 = 0 -1 = 10 -2 = 0 -3 = 1 -4 = 1 -5 = 2³² -6 = 1 -> into -At opcode 1.14: Const { destination: RegisterIndex(5), value: Value { inner: 1 } } -... -> memory -0 = 1 -> -``` - -In the example above: we start with clean memory, then step through a `Store` opcode which stores the value of register 3 (1) into the memory address stored in register 0 (0). Thus now `memory` shows memory address 0 contains value 1. - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: - -#### `memset [Memory address] [New value]` - -Update a memory cell with the given value. For example: - -``` -> memory -0 = 1 -> memset 0 2 -> memory -0 = 2 -> memset 1 4 -> memory -0 = 2 -1 = 4 -> -``` - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_vscode.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_vscode.md deleted file mode 100644 index c027332b3b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/debugger/debugger_vscode.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: VS Code Debugger -description: - VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -# VS Code Noir Debugger Reference - -The Noir debugger enabled by the vscode-noir extension ships with default settings such that the most common scenario should run without any additional configuration steps. - -These defaults can nevertheless be overridden by defining a launch configuration file. This page provides a reference for the properties you can override via a launch configuration file, as well as documenting the Nargo `dap` command, which is a dependency of the VS Code Noir debugger. - - -## Creating and editing launch configuration files - -To create a launch configuration file from VS Code, open the _debug pane_, and click on _create a launch.json file_. - -![Creating a launch configuration file](@site/static/img/debugger/ref1-create-launch.png) - -A `launch.json` file will be created, populated with basic defaults. - -### Noir Debugger launch.json properties - -#### projectFolder - -_String, optional._ - -Absolute path to the Nargo project to debug. By default, it is dynamically determined by looking for the nearest `Nargo.toml` file to the active file at the moment of launching the debugger. - -#### proverName - -_String, optional._ - -Name of the prover input to use. Defaults to `Prover`, which looks for a file named `Prover.toml` at the `projectFolder`. - -#### generateAcir - -_Boolean, optional._ - -If true, generate ACIR opcodes instead of unconstrained opcodes which will be closer to release binaries but less convenient for debugging. Defaults to `false`. - -#### skipInstrumentation - -_Boolean, optional._ - -Skips variables debugging instrumentation of code, making debugging less convenient but the resulting binary smaller and closer to production. Defaults to `false`. - -:::note -Skipping instrumentation causes the debugger to be unable to inspect local variables. -::: - -## `nargo dap [OPTIONS]` - -When run without any option flags, it starts the Nargo Debug Adapter Protocol server, which acts as the debugging backend for the VS Code Noir Debugger. - -All option flags are related to preflight checks. The Debug Adapter Protocol specifies how errors are to be informed from a running DAP server, but it doesn't specify mechanisms to communicate server initialization errors between the DAP server and its client IDE. - -Thus `nargo dap` ships with a _preflight check_ mode. If flag `--preflight-check` and the rest of the `--preflight-*` flags are provided, Nargo will run the same initialization routine except it will not start the DAP server. - -`vscode-noir` will then run `nargo dap` in preflight check mode first before a debugging session starts. If the preflight check ends in error, vscode-noir will present stderr and stdout output from this process through its own Output pane in VS Code. This makes it possible for users to diagnose what pieces of configuration might be wrong or missing in case of initialization errors. - -If the preflight check succeeds, `vscode-noir` proceeds to start the DAP server normally but running `nargo dap` without any additional flags. - -### Options - -| Option | Description | -| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `--preflight-check` | If present, dap runs in preflight check mode. | -| `--preflight-project-folder ` | Absolute path to the project to debug for preflight check. | -| `--preflight-prover-name ` | Name of prover file to use for preflight check | -| `--preflight-generate-acir` | Optional. If present, compile in ACIR mode while running preflight check. | -| `--preflight-skip-instrumentation` | Optional. If present, compile without introducing debug instrumentation while running preflight check. | -| `-h, --help` | Print help. | diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/nargo_commands.md deleted file mode 100644 index 218fcfb0c8c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/reference/nargo_commands.md +++ /dev/null @@ -1,381 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/debugger.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/debugger.md deleted file mode 100644 index 9b7565ba9ff..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/debugger.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Debugger -description: Learn about the Noir Debugger, in its REPL or VS Code versions. -keywords: [Nargo, VSCode, Visual Studio Code, REPL, Debugger] -sidebar_position: 2 ---- - -# Noir Debugger - -There are currently two ways of debugging Noir programs: - -1. From VS Code, via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). -2. Via the REPL debugger, which ships with Nargo. - -In order to use either version of the debugger, you will need to install recent enough versions of Noir, [Nargo](../getting_started/installation/index.md) and vscode-noir: - -- Noir & Nargo ≥0.28.0 -- Noir's VS Code extension ≥0.0.11 - -:::info -At the moment, the debugger supports debugging binary projects, but not contracts. -::: - -We cover the VS Code Noir debugger more in depth in [its VS Code debugger how-to guide](../how_to/debugger/debugging_with_vs_code.md) and [the reference](../reference/debugger/debugger_vscode.md). - -The REPL debugger is discussed at length in [the REPL debugger how-to guide](../how_to/debugger/debugging_with_the_repl.md) and [the reference](../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tutorials/noirjs_app.md deleted file mode 100644 index 3dd9fe7d2b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.28.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.27.x matches `noir_js@0.27.x`, etc. - -In this guide, we will be pinned to 0.27.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -`nargo new circuit` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -`nargo compile` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from "vite"; -import copy from "rollup-plugin-copy"; - -export default defineConfig({ - esbuild: { - target: "esnext", - }, - optimizeDeps: { - esbuildOptions: { - target: "esnext", - }, - }, - plugins: [ - copy({ - targets: [ - { src: "node_modules/**/*.wasm", dest: "node_modules/.vite/dist" }, - ], - copySync: true, - hook: "buildStart", - }), - ], - server: { - port: 3000, - }, -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.27.0 @noir-lang/noir_js@0.27.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import('@noir-lang/noirc_abi').then((module) => - module.default(new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString()), - ), - import('@noir-lang/acvm_js').then((module) => - module.default(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()), - ), - ]); -}; - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend, BarretenbergVerifier as Verifier } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verificationKey = await backend.getVerificationKey(); -const verifier = new Verifier(); -const isValid = await verifier.verifyProof(proof, verificationKey); -if (isValid) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index d65151da0ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 2 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = {"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"param_witnesses":{"x":[{"start":0,"end":1}],"y":[{"start":1,"end":2}]},"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"},"return_witnesses":[4]},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/_category_.json deleted file mode 100644 index cc2cbb1c253..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugging", - "position": 5, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_the_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_the_repl.md deleted file mode 100644 index 09e5bae68ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_the_repl.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Using the REPL Debugger -description: - Step by step guide on how to debug your Noir circuits with the REPL Debugger. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -#### Pre-requisites - -In order to use the REPL debugger, first you need to install recent enough versions of Nargo and vscode-noir. - -## Debugging a simple circuit - -Let's debug a simple circuit: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -To start the REPL debugger, using a terminal, go to a Noir circuit's home directory. Then: - -`$ nargo debug` - -You should be seeing this in your terminal: - -``` -[main] Starting debugger -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:9 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> -``` - -The debugger displays the current Noir code location, and it is now waiting for us to drive it. - -Let's first take a look at the available commands. For that we'll use the `help` command. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -Some commands operate only for unconstrained functions, such as `memory` and `memset`. If you try to use them while execution is paused at an ACIR opcode, the debugger will simply inform you that you are not executing unconstrained code: - -``` -> memory -Unconstrained VM memory not available -> -``` - -Before continuing, we can take a look at the initial witness map: - -``` -> witness -_0 = 1 -_1 = 2 -> -``` - -Cool, since `x==1`, `y==2`, and we want to check that `x != y`, our circuit should succeed. At this point we could intervene and use the witness setter command to change one of the witnesses. Let's set `y=3`, then back to 2, so we don't affect the expected result: - -``` -> witness -_0 = 1 -_1 = 2 -> witness 1 3 -_1 = 3 -> witness -_0 = 1 -_1 = 3 -> witness 1 2 -_1 = 2 -> witness -_0 = 1 -_1 = 2 -> -``` - -Now we can inspect the current state of local variables. For that we use the `vars` command. - -``` -> vars -> -``` - -We currently have no vars in context, since we are at the entry point of the program. Let's use `next` to execute until the next point in the program. - -``` -> vars -> next -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:20 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> vars -x:Field = 0x01 -``` - -As a result of stepping, the variable `x`, whose initial value comes from the witness map, is now in context and returned by `vars`. - -``` -> next - 1 fn main(x : Field, y : pub Field) { - 2 -> assert(x != y); - 3 } -> vars -y:Field = 0x02 -x:Field = 0x01 -``` - -Stepping again we can finally see both variables and their values. And now we can see that the next assertion should succeed. - -Let's continue to the end: - -``` -> continue -(Continuing execution...) -Finished execution -> q -[main] Circuit witness successfully solved -``` - -Upon quitting the debugger after a solved circuit, the resulting circuit witness gets saved, equivalent to what would happen if we had run the same circuit with `nargo execute`. - -We just went through the basics of debugging using Noir REPL debugger. For a comprehensive reference, check out [the reference page](../../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_vs_code.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_vs_code.md deleted file mode 100644 index a5858c1a5eb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/debugger/debugging_with_vs_code.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Using the VS Code Debugger -description: - Step by step guide on how to debug your Noir circuits with the VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -This guide will show you how to use VS Code with the vscode-noir extension to debug a Noir project. - -#### Pre-requisites - -- Nargo -- vscode-noir -- A Noir project with a `Nargo.toml`, `Prover.toml` and at least one Noir (`.nr`) containing an entry point function (typically `main`). - -## Running the debugger - -The easiest way to start debugging is to open the file you want to debug, and press `F5`. This will cause the debugger to launch, using your `Prover.toml` file as input. - -You should see something like this: - -![Debugger launched](@site/static/img/debugger/1-started.png) - -Let's inspect the state of the program. For that, we open VS Code's _Debug pane_. Look for this icon: - -![Debug pane icon](@site/static/img/debugger/2-icon.png) - -You will now see two categories of variables: Locals and Witness Map. - -![Debug pane expanded](@site/static/img/debugger/3-debug-pane.png) - -1. **Locals**: variables of your program. At this point in execution this section is empty, but as we step through the code it will get populated by `x`, `result`, `digest`, etc. - -2. **Witness map**: these are initially populated from your project's `Prover.toml` file. In this example, they will be used to populate `x` and `result` at the beginning of the `main` function. - -Most of the time you will probably be focusing mostly on locals, as they represent the high level state of your program. - -You might be interested in inspecting the witness map in case you are trying to solve a really low level issue in the compiler or runtime itself, so this concerns mostly advanced or niche users. - -Let's step through the program, by using the debugger buttons or their corresponding keyboard shortcuts. - -![Debugger buttons](@site/static/img/debugger/4-debugger-buttons.png) - -Now we can see in the variables pane that there's values for `digest`, `result` and `x`. - -![Inspecting locals](@site/static/img/debugger/5-assert.png) - -We can also inspect the values of variables by directly hovering on them on the code. - -![Hover locals](@site/static/img/debugger/6-hover.png) - -Let's set a break point at the `keccak256` function, so we can continue execution up to the point when it's first invoked without having to go one step at a time. - -We just need to click the to the right of the line number 18. Once the breakpoint appears, we can click the `continue` button or use its corresponding keyboard shortcut (`F5` by default). - -![Breakpoint](@site/static/img/debugger/7-break.png) - -Now we are debugging the `keccak256` function, notice the _Call Stack pane_ at the lower right. This lets us inspect the current call stack of our process. - -That covers most of the current debugger functionalities. Check out [the reference](../../reference/debugger/debugger_vscode.md) for more details on how to configure the debugger. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-oracles.md deleted file mode 100644 index 8cf8035a5c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a field element *as a string*. For example: - -```json -{ "values": [{ "Array": ["1", "2"] }]} -{ "values": [{ "Single": "1" }]} -{ "values": [{ "Single": "1" }, { "Array": ["1", "2"] }]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e5ce3b7bc22..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, `Polygon zkEVM` does not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo -- zkSync - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/merkle-proof.mdx deleted file mode 100644 index 16c425bed76..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] -sidebar_position: 4 ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 1c6b375db49..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,155 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. The Noir frontend supports both unsigned and signed integer types. The allowed sizes are 1, 8, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4eccc677b80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` - -### as_array - -Converts this slice into an array. - -Make sure to specify the size of the resulting array. -Panics if the resulting array length is different than the slice's length. - -```rust -fn as_array(self) -> [T; N] -``` - -Example: - -```rust -fn main() { - let slice = &[5, 6]; - - // Always specify the length of the resulting array! - let array: [Field; 2] = slice.as_array(); - - assert(array[0] == slice[0]); - assert(array[1] == slice[1]); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/functions.md deleted file mode 100644 index f656cdfd97a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/ops.md deleted file mode 100644 index c35c36c38a9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer, shift must be u8 | -| >> | Right shift an integer by another integer amount | Types must be integer, shift must be u8 | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/oracles.md deleted file mode 100644 index aa380b5f7b8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/oracles.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -:::note - -This is an experimental feature that is not fully documented. If you notice any outdated information or potential improvements to this page, pull request contributions are very welcome: https://github.com/noir-lang/noir - -::: - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` - -The timeout for when using an external RPC oracle resolver can be set with the `NARGO_FOREIGN_CALL_TIMEOUT` environment variable. This timeout is in units of milliseconds. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bigint.md deleted file mode 100644 index 2bfdeec6631..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L14-L19 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L70-L78 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - // Construct a big integer from a slice of bytes - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - // Construct a big integer from an array of 32 bytes - let a = Secpk1Fq::from_le_bytes_32([1;32]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index e8b62f21d4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Fixed base scalar multiplication](./cryptographic_primitives/scalar.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index ce4529f6e57..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 47faa99aba6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,570 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a poseidon2 hasher -use dep::std::hash::poseidon2::Poseidon2Hasher; -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index fcfd7e07aa0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index f8a1c25ccf6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.29.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.29.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 3b83d9ec31a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. -Specify a message_size to hash only the first `message_size` bytes of the input. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L10-L12 - - -example: -```rust title="sha256_var" showLineNumbers -let digest = std::hash::sha256_var([x as u8], 1); -``` -> Source code: test_programs/execution_success/sha256/src/main.nr#L17-L19 - - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::sha256::sha256_var(x, 4); -} -``` - - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L16-L18 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L22-L24 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L46-L48 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint { -``` -> Source code: noir_stdlib/src/hash.nr#L27-L34 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L68-L70 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/scalar.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/scalar.mdx deleted file mode 100644 index df411ca5443..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/scalar.mdx +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplications over a fixed base in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## scalar_mul::fixed_base_embedded_curve - -Performs scalar multiplication over the embedded curve whose coordinates are defined by the -configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -```rust title="fixed_base_embedded_curve" showLineNumbers -pub fn fixed_base_embedded_curve( - low: Field, - high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/scalar_mul.nr#L27-L32 - - -example - -```rust -fn main(x : Field) { - let scal = std::scalar_mul::fixed_base_embedded_curve(x); - println(scal); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/recursion.md deleted file mode 100644 index f33c285cf4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/traits.md deleted file mode 100644 index 04dc40f0dac..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/traits.md +++ /dev/null @@ -1,410 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(self) -> T; -} - -impl Into for U where T: From { - fn into(self) -> T { - T::from(self) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -`std::cmp` also provides `max` and `min` functions for any type which implements the `Ord` trait. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L17-L21 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L33-L37 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L49-L53 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L65-L69 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L79-L83 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L95-L99 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L111-L115 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L127-L131 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops.nr#L142-L146 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index d7249d24330..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,160 +0,0 @@ -# BarretenbergBackend - -## Extends - -- `BarretenbergVerifierBackend` - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -#### Inherited from - -BarretenbergVerifierBackend.constructor - -## Properties - -| Property | Type | Description | Inheritance | -| :------ | :------ | :------ | :------ | -| `acirComposer` | `any` | - | BarretenbergVerifierBackend.acirComposer | -| `acirUncompressedBytecode` | `Uint8Array` | - | BarretenbergVerifierBackend.acirUncompressedBytecode | -| `api` | `Barretenberg` | - | BarretenbergVerifierBackend.api | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - | BarretenbergVerifierBackend.options | - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Inherited from - -BarretenbergVerifierBackend.destroy - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### getVerificationKey() - -```ts -getVerificationKey(): Promise -``` - -#### Returns - -`Promise`\<`Uint8Array`\> - -#### Inherited from - -BarretenbergVerifierBackend.getVerificationKey - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Inherited from - -BarretenbergVerifierBackend.verifyProof - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md deleted file mode 100644 index 500276ea748..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md +++ /dev/null @@ -1,58 +0,0 @@ -# BarretenbergVerifier - -## Constructors - -### new BarretenbergVerifier(options) - -```ts -new BarretenbergVerifier(options): BarretenbergVerifier -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergVerifier`](BarretenbergVerifier.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### verifyProof() - -```ts -verifyProof(proofData, verificationKey): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | -| `verificationKey` | `Uint8Array` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index 64971973196..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | -| [BarretenbergVerifier](classes/BarretenbergVerifier.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): Backend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -[`Backend`](index.md#backend) - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index d7d5128f9e3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier","label":"BarretenbergVerifier"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 45dd62ee57e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | -| `backend`? | `any` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index cca6b3ace41..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,54 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -*** - -### ProofData - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index c6d8125eaad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/_category_.json deleted file mode 100644 index 27869205ad3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugger", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_known_limitations.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_known_limitations.md deleted file mode 100644 index 936d416ac4b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_known_limitations.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Known limitations -description: - An overview of known limitations of the current version of the Noir debugger -keywords: - [ - Nargo, - Noir Debugger, - VS Code, - ] -sidebar_position: 2 ---- - -# Debugger Known Limitations - -There are currently some limits to what the debugger can observe. - -## Mutable references - -The debugger is currently blind to any state mutated via a mutable reference. For example, in: - -``` -let mut x = 1; -let y = &mut x; -*y = 2; -``` - -The update on `x` will not be observed by the debugger. That means, when running `vars` from the debugger REPL, or inspecting the _local variables_ pane in the VS Code debugger, `x` will appear with value 1 despite having executed `*y = 2;`. - -## Variables of type function or mutable references are opaque - -When inspecting variables, any variable of type `Function` or `MutableReference` will render its value as `<>` or `<>`. - -## Debugger instrumentation affects resulting ACIR - -In order to make the state of local variables observable, the debugger compiles Noir circuits interleaving foreign calls that track any mutations to them. While this works (except in the cases described above) and doesn't introduce any behavior changes, it does as a side effect produce bigger bytecode. In particular, when running the command `opcodes` on the REPL debugger, you will notice Unconstrained VM blocks that look like this: - -``` -... -5 BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [], q_c: 2 }), Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(2))], q_c: 0 })] - | outputs=[] - 5.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 5.1 | Mov { destination: RegisterIndex(3), source: RegisterIndex(1) } - 5.2 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 5.3 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 5.4 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 5.5 | Mov { destination: RegisterIndex(3), source: RegisterIndex(3) } - 5.6 | Call { location: 8 } - 5.7 | Stop - 5.8 | ForeignCall { function: "__debug_var_assign", destinations: [], inputs: [RegisterIndex(RegisterIndex(2)), RegisterIndex(RegisterIndex(3))] } -... -``` - -If you are interested in debugging/inspecting compiled ACIR without these synthetic changes, you can invoke the REPL debugger with the `--skip-instrumentation` flag or launch the VS Code debugger with the `skipConfiguration` property set to true in its launch configuration. You can find more details about those in the [Debugger REPL reference](debugger_repl.md) and the [VS Code Debugger reference](debugger_vscode.md). - -:::note -Skipping debugger instrumentation means you won't be able to inspect values of local variables. -::: - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_repl.md deleted file mode 100644 index 46e2011304e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_repl.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: REPL Debugger -description: - Noir Debugger REPL options and commands. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -## Running the REPL debugger - -`nargo debug [OPTIONS] [WITNESS_NAME]` - -Runs the Noir REPL debugger. If a `WITNESS_NAME` is provided the debugger writes the resulting execution witness to a `WITNESS_NAME` file. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover]| -| `--package ` | The name of the package to debug | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -None of these options are required. - -:::note -Since the debugger starts by compiling the target package, all Noir compiler options are also available. Check out the [compiler reference](../nargo_commands.md#nargo-compile) to learn more about the compiler options. -::: - -## REPL commands - -Once the debugger is running, it accepts the following commands. - -#### `help` (h) - -Displays the menu of available commands. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) value - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -### Stepping through programs - -#### `next` (n) - -Step until the next Noir source code location. While other commands, such as [`into`](#into-i) and [`step`](#step-s), allow for finer grained control of the program's execution at the opcode level, `next` is source code centric. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `next` here would cause the debugger to jump to the definition of `deep_entry_point` (if available). - -If you want to step over `deep_entry_point` and go straight to line 8, use [the `over` command](#over) instead. - -#### `over` - -Step until the next source code location, without diving into function calls. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `over` here would cause the debugger to execute until line 8 (`multiple_values_entry_point(x);`). - -If you want to step into `deep_entry_point` instead, use [the `next` command](#next-n). - -#### `out` - -Step until the end of the current function call. For example: - -``` - 3 ... - 4 fn main(x: u32) { - 5 assert(entry_point(x) == 2); - 6 swap_entry_point(x, x + 1); - 7 -> assert(deep_entry_point(x) == 4); - 8 multiple_values_entry_point(x); - 9 } - 10 - 11 unconstrained fn returns_multiple_values(x: u32) -> (u32, u32, u32, u32) { - 12 ... - ... - 55 - 56 unconstrained fn deep_entry_point(x: u32) -> u32 { - 57 -> level_1(x + 1) - 58 } - -``` - -Running `out` here will resume execution until line 8. - -#### `step` (s) - -Skips to the next ACIR code. A compiled Noir program is a sequence of ACIR opcodes. However, an unconstrained VM opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `step` command at this point would result in the debugger stopping at ACIR opcode 2, `EXPR`, skipping unconstrained computation steps. - -Use [the `into` command](#into-i) instead if you want to follow unconstrained computation step by step. - -#### `into` (i) - -Steps into the next opcode. A compiled Noir program is a sequence of ACIR opcodes. However, a BRILLIG opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `into` command at this point would result in the debugger stopping at opcode 1.0, `Mov ...`, allowing the debugger user to follow unconstrained computation step by step. - -Use [the `step` command](#step-s) instead if you want to skip to the next ACIR code directly. - -#### `continue` (c) - -Continues execution until the next breakpoint, or the end of the program. - -#### `restart` (res) - -Interrupts execution, and restarts a new debugging session from scratch. - -#### `opcodes` (o) - -Display the program's ACIR opcode sequence. For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -### Breakpoints - -#### `break [Opcode]` (or shorthand `b [Opcode]`) - -Sets a breakpoint on the specified opcode index. To get a list of the program opcode numbers, see [the `opcode` command](#opcodes-o). For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -In this example, issuing a `break 1.2` command adds break on opcode 1.2, as denoted by the `*` character: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | * Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -Running [the `continue` command](#continue-c) at this point would cause the debugger to execute the program until opcode 1.2. - -#### `delete [Opcode]` (or shorthand `d [Opcode]`) - -Deletes a breakpoint at an opcode location. Usage is analogous to [the `break` command](#). - -### Variable inspection - -#### vars - -Show variable values available at this point in execution. - -:::note -The ability to inspect variable values from the debugger depends on compilation to be run in a special debug instrumentation mode. This instrumentation weaves variable tracing code with the original source code. - -So variable value inspection comes at the expense of making the resulting ACIR bytecode bigger and harder to understand and optimize. - -If you find this compromise unacceptable, you can run the debugger with the flag `--skip-debug-instrumentation`. This will compile your circuit without any additional debug information, so the resulting ACIR bytecode will be identical to the one produced by standard Noir compilation. However, if you opt for this, the `vars` command will not be available while debugging. -::: - - -### Stacktrace - -#### `stacktrace` - -Displays the current stack trace. - - -### Witness map - -#### `witness` (w) - -Show witness map. For example: - -``` -_0 = 0 -_1 = 2 -_2 = 1 -``` - -#### `witness [Witness Index]` - -Display a single witness from the witness map. For example: - -``` -> witness 1 -_1 = 2 -``` - -#### `witness [Witness Index] [New value]` - -Overwrite the given index with a new value. For example: - -``` -> witness 1 3 -_1 = 3 -``` - - -### Unconstrained VM memory - -#### `memory` - -Show unconstrained VM memory state. For example: - -``` -> memory -At opcode 1.13: Store { destination_pointer: RegisterIndex(0), source: RegisterIndex(3) } -... -> registers -0 = 0 -1 = 10 -2 = 0 -3 = 1 -4 = 1 -5 = 2³² -6 = 1 -> into -At opcode 1.14: Const { destination: RegisterIndex(5), value: Value { inner: 1 } } -... -> memory -0 = 1 -> -``` - -In the example above: we start with clean memory, then step through a `Store` opcode which stores the value of register 3 (1) into the memory address stored in register 0 (0). Thus now `memory` shows memory address 0 contains value 1. - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: - -#### `memset [Memory address] [New value]` - -Update a memory cell with the given value. For example: - -``` -> memory -0 = 1 -> memset 0 2 -> memory -0 = 2 -> memset 1 4 -> memory -0 = 2 -1 = 4 -> -``` - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_vscode.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_vscode.md deleted file mode 100644 index c027332b3b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/debugger/debugger_vscode.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: VS Code Debugger -description: - VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -# VS Code Noir Debugger Reference - -The Noir debugger enabled by the vscode-noir extension ships with default settings such that the most common scenario should run without any additional configuration steps. - -These defaults can nevertheless be overridden by defining a launch configuration file. This page provides a reference for the properties you can override via a launch configuration file, as well as documenting the Nargo `dap` command, which is a dependency of the VS Code Noir debugger. - - -## Creating and editing launch configuration files - -To create a launch configuration file from VS Code, open the _debug pane_, and click on _create a launch.json file_. - -![Creating a launch configuration file](@site/static/img/debugger/ref1-create-launch.png) - -A `launch.json` file will be created, populated with basic defaults. - -### Noir Debugger launch.json properties - -#### projectFolder - -_String, optional._ - -Absolute path to the Nargo project to debug. By default, it is dynamically determined by looking for the nearest `Nargo.toml` file to the active file at the moment of launching the debugger. - -#### proverName - -_String, optional._ - -Name of the prover input to use. Defaults to `Prover`, which looks for a file named `Prover.toml` at the `projectFolder`. - -#### generateAcir - -_Boolean, optional._ - -If true, generate ACIR opcodes instead of unconstrained opcodes which will be closer to release binaries but less convenient for debugging. Defaults to `false`. - -#### skipInstrumentation - -_Boolean, optional._ - -Skips variables debugging instrumentation of code, making debugging less convenient but the resulting binary smaller and closer to production. Defaults to `false`. - -:::note -Skipping instrumentation causes the debugger to be unable to inspect local variables. -::: - -## `nargo dap [OPTIONS]` - -When run without any option flags, it starts the Nargo Debug Adapter Protocol server, which acts as the debugging backend for the VS Code Noir Debugger. - -All option flags are related to preflight checks. The Debug Adapter Protocol specifies how errors are to be informed from a running DAP server, but it doesn't specify mechanisms to communicate server initialization errors between the DAP server and its client IDE. - -Thus `nargo dap` ships with a _preflight check_ mode. If flag `--preflight-check` and the rest of the `--preflight-*` flags are provided, Nargo will run the same initialization routine except it will not start the DAP server. - -`vscode-noir` will then run `nargo dap` in preflight check mode first before a debugging session starts. If the preflight check ends in error, vscode-noir will present stderr and stdout output from this process through its own Output pane in VS Code. This makes it possible for users to diagnose what pieces of configuration might be wrong or missing in case of initialization errors. - -If the preflight check succeeds, `vscode-noir` proceeds to start the DAP server normally but running `nargo dap` without any additional flags. - -### Options - -| Option | Description | -| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `--preflight-check` | If present, dap runs in preflight check mode. | -| `--preflight-project-folder ` | Absolute path to the project to debug for preflight check. | -| `--preflight-prover-name ` | Name of prover file to use for preflight check | -| `--preflight-generate-acir` | Optional. If present, compile in ACIR mode while running preflight check. | -| `--preflight-skip-instrumentation` | Optional. If present, compile without introducing debug instrumentation while running preflight check. | -| `-h, --help` | Print help. | diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/nargo_commands.md deleted file mode 100644 index 218fcfb0c8c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/reference/nargo_commands.md +++ /dev/null @@ -1,381 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/debugger.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/debugger.md deleted file mode 100644 index 9b7565ba9ff..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/debugger.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Debugger -description: Learn about the Noir Debugger, in its REPL or VS Code versions. -keywords: [Nargo, VSCode, Visual Studio Code, REPL, Debugger] -sidebar_position: 2 ---- - -# Noir Debugger - -There are currently two ways of debugging Noir programs: - -1. From VS Code, via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). -2. Via the REPL debugger, which ships with Nargo. - -In order to use either version of the debugger, you will need to install recent enough versions of Noir, [Nargo](../getting_started/installation/index.md) and vscode-noir: - -- Noir & Nargo ≥0.28.0 -- Noir's VS Code extension ≥0.0.11 - -:::info -At the moment, the debugger supports debugging binary projects, but not contracts. -::: - -We cover the VS Code Noir debugger more in depth in [its VS Code debugger how-to guide](../how_to/debugger/debugging_with_vs_code.md) and [the reference](../reference/debugger/debugger_vscode.md). - -The REPL debugger is discussed at length in [the REPL debugger how-to guide](../how_to/debugger/debugging_with_the_repl.md) and [the reference](../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tutorials/noirjs_app.md deleted file mode 100644 index 3dd9fe7d2b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.29.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.27.x matches `noir_js@0.27.x`, etc. - -In this guide, we will be pinned to 0.27.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -`nargo new circuit` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -`nargo compile` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from "vite"; -import copy from "rollup-plugin-copy"; - -export default defineConfig({ - esbuild: { - target: "esnext", - }, - optimizeDeps: { - esbuildOptions: { - target: "esnext", - }, - }, - plugins: [ - copy({ - targets: [ - { src: "node_modules/**/*.wasm", dest: "node_modules/.vite/dist" }, - ], - copySync: true, - hook: "buildStart", - }), - ], - server: { - port: 3000, - }, -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.27.0 @noir-lang/noir_js@0.27.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import('@noir-lang/noirc_abi').then((module) => - module.default(new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString()), - ), - import('@noir-lang/acvm_js').then((module) => - module.default(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()), - ), - ]); -}; - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend, BarretenbergVerifier as Verifier } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verificationKey = await backend.getVerificationKey(); -const verifier = new Verifier(); -const isValid = await verifier.verifyProof(proof, verificationKey); -if (isValid) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/index.md deleted file mode 100644 index 743c4d8d634..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,142 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo, it is time to make our first hello world program! - -## Create a Project Directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our Noir programs. - -For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by -running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Create Our First Nargo Project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for -> demonstration. -> -> In production, the common practice is to name the project folder as `circuits` for better -> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, -> `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -## Build In/Output Files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -Two additional files would be generated in your project directory: - -_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. - -## Prove Our Noir Program - -Now that the project is set up, we can create a proof of correct execution of our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Prove the valid execution of your Noir program: - -```sh -nargo prove -``` - -A new folder _proofs_ would then be generated in your project directory, containing the proof file -`.proof`, where the project name is defined in Nargo.toml. - -The _Verifier.toml_ file would also be updated with the public values computed from program -execution (in this case the value of `y`): - -```toml -y = "0x0000000000000000000000000000000000000000000000000000000000000002" -``` - -> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. - -## Verify Our Noir Program - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the -proof file. - -Verify your proof by running: - -```sh -nargo verify -``` - -The verification will complete in silence if it is successful. If it fails, it will log the -corresponding error instead. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 6160a102c6c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,199 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML - files, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. We elaborate on the project -structure and what the `prove` and `verify` commands did. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Verifier.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Verifier.toml - -_Verifier.toml_ contains public in/output values computed when executing the Noir program. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the -prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when -verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is -constrained by the proof of the execution of said program (i.e. if the condition was not met, the -verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and -public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo prove` is executed, two processes happen: - -1. Noir creates a proof that `x`, which holds the value of `1`, and `y`, which holds the value of `2`, - is not equal. This inequality constraint is due to the line `assert(x != y)`. - -2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: - -```bash -nargo prove -p OtherProver -``` - -## Verifying a Proof - -When the command `nargo verify` is executed, two processes happen: - -1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) - -2. If that file is found, the proof's validity is checked - -> **Note:** The validity of the proof is linked to the current Noir program; if the program is -> changed and the verifier verifies the proof, it will fail because the proof is not valid for the -> _modified_ Noir program. - -In production, the prover and the verifier are usually two separate entities. A prover would -retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the -verifier. The verifier would then retrieve the public inputs, usually from external sources, and -verify the validity of the proof against it. - -Take a private asset transfer as an example: - -A person using a browser as the prover would retrieve private inputs locally (e.g. the user's private key) and -public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof -and submit it to the verifier smart contract. - -The verifier contract would then draw the user's encrypted balance directly from the blockchain and -verify the proof submitted against it. If the verification passes, additional functions in the -verifier contract could trigger (e.g. approve the asset transfer). - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/index.md deleted file mode 100644 index 4ef86aa5914..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/index.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is the one-stop-shop for almost everything related with Noir. The name comes from our love for Rust and its package manager `cargo`. - -With `nargo`, you can start new projects, compile, execute, prove, verify, test, generate solidity contracts, and do pretty much all that is available in Noir. - -Similarly to `rustup`, we also maintain an easy installation method that covers most machines: `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index d65151da0ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,113 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 2 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = {"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"param_witnesses":{"x":[{"start":0,"end":1}],"y":[{"start":1,"end":2}]},"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"},"return_witnesses":[4]},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/_category_.json deleted file mode 100644 index cc2cbb1c253..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugging", - "position": 5, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_the_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_the_repl.md deleted file mode 100644 index 09e5bae68ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_the_repl.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Using the REPL Debugger -description: - Step by step guide on how to debug your Noir circuits with the REPL Debugger. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -#### Pre-requisites - -In order to use the REPL debugger, first you need to install recent enough versions of Nargo and vscode-noir. - -## Debugging a simple circuit - -Let's debug a simple circuit: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -To start the REPL debugger, using a terminal, go to a Noir circuit's home directory. Then: - -`$ nargo debug` - -You should be seeing this in your terminal: - -``` -[main] Starting debugger -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:9 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> -``` - -The debugger displays the current Noir code location, and it is now waiting for us to drive it. - -Let's first take a look at the available commands. For that we'll use the `help` command. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -Some commands operate only for unconstrained functions, such as `memory` and `memset`. If you try to use them while execution is paused at an ACIR opcode, the debugger will simply inform you that you are not executing unconstrained code: - -``` -> memory -Unconstrained VM memory not available -> -``` - -Before continuing, we can take a look at the initial witness map: - -``` -> witness -_0 = 1 -_1 = 2 -> -``` - -Cool, since `x==1`, `y==2`, and we want to check that `x != y`, our circuit should succeed. At this point we could intervene and use the witness setter command to change one of the witnesses. Let's set `y=3`, then back to 2, so we don't affect the expected result: - -``` -> witness -_0 = 1 -_1 = 2 -> witness 1 3 -_1 = 3 -> witness -_0 = 1 -_1 = 3 -> witness 1 2 -_1 = 2 -> witness -_0 = 1 -_1 = 2 -> -``` - -Now we can inspect the current state of local variables. For that we use the `vars` command. - -``` -> vars -> -``` - -We currently have no vars in context, since we are at the entry point of the program. Let's use `next` to execute until the next point in the program. - -``` -> vars -> next -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:20 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> vars -x:Field = 0x01 -``` - -As a result of stepping, the variable `x`, whose initial value comes from the witness map, is now in context and returned by `vars`. - -``` -> next - 1 fn main(x : Field, y : pub Field) { - 2 -> assert(x != y); - 3 } -> vars -y:Field = 0x02 -x:Field = 0x01 -``` - -Stepping again we can finally see both variables and their values. And now we can see that the next assertion should succeed. - -Let's continue to the end: - -``` -> continue -(Continuing execution...) -Finished execution -> q -[main] Circuit witness successfully solved -``` - -Upon quitting the debugger after a solved circuit, the resulting circuit witness gets saved, equivalent to what would happen if we had run the same circuit with `nargo execute`. - -We just went through the basics of debugging using Noir REPL debugger. For a comprehensive reference, check out [the reference page](../../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_vs_code.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_vs_code.md deleted file mode 100644 index a5858c1a5eb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/debugger/debugging_with_vs_code.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Using the VS Code Debugger -description: - Step by step guide on how to debug your Noir circuits with the VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -This guide will show you how to use VS Code with the vscode-noir extension to debug a Noir project. - -#### Pre-requisites - -- Nargo -- vscode-noir -- A Noir project with a `Nargo.toml`, `Prover.toml` and at least one Noir (`.nr`) containing an entry point function (typically `main`). - -## Running the debugger - -The easiest way to start debugging is to open the file you want to debug, and press `F5`. This will cause the debugger to launch, using your `Prover.toml` file as input. - -You should see something like this: - -![Debugger launched](@site/static/img/debugger/1-started.png) - -Let's inspect the state of the program. For that, we open VS Code's _Debug pane_. Look for this icon: - -![Debug pane icon](@site/static/img/debugger/2-icon.png) - -You will now see two categories of variables: Locals and Witness Map. - -![Debug pane expanded](@site/static/img/debugger/3-debug-pane.png) - -1. **Locals**: variables of your program. At this point in execution this section is empty, but as we step through the code it will get populated by `x`, `result`, `digest`, etc. - -2. **Witness map**: these are initially populated from your project's `Prover.toml` file. In this example, they will be used to populate `x` and `result` at the beginning of the `main` function. - -Most of the time you will probably be focusing mostly on locals, as they represent the high level state of your program. - -You might be interested in inspecting the witness map in case you are trying to solve a really low level issue in the compiler or runtime itself, so this concerns mostly advanced or niche users. - -Let's step through the program, by using the debugger buttons or their corresponding keyboard shortcuts. - -![Debugger buttons](@site/static/img/debugger/4-debugger-buttons.png) - -Now we can see in the variables pane that there's values for `digest`, `result` and `x`. - -![Inspecting locals](@site/static/img/debugger/5-assert.png) - -We can also inspect the values of variables by directly hovering on them on the code. - -![Hover locals](@site/static/img/debugger/6-hover.png) - -Let's set a break point at the `keccak256` function, so we can continue execution up to the point when it's first invoked without having to go one step at a time. - -We just need to click the to the right of the line number 18. Once the breakpoint appears, we can click the `continue` button or use its corresponding keyboard shortcut (`F5` by default). - -![Breakpoint](@site/static/img/debugger/7-break.png) - -Now we are debugging the `keccak256` function, notice the _Call Stack pane_ at the lower right. This lets us inspect the current call stack of our process. - -That covers most of the current debugger functionalities. Check out [the reference](../../reference/debugger/debugger_vscode.md) for more details on how to configure the debugger. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-oracles.md deleted file mode 100644 index 8cf8035a5c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,276 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("getSqrt", async (params) => { - const values = params[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -:::tip - -Brillig expects an object with an array of values. Each value is an object declaring to be `Single` or `Array` and returning a field element *as a string*. For example: - -```json -{ "values": [{ "Array": ["1", "2"] }]} -{ "values": [{ "Single": "1" }]} -{ "values": [{ "Single": "1" }, { "Array": ["1", "2"] }]} -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test`, `nargo execute` and `nargo prove` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.generateProof(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test` or `nargo prove`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-recursion.md deleted file mode 100644 index 4c45bb87ae2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,179 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit, backend) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main, backends.main), - recursive: new Noir(circuits.recursive, backends.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const recursiveProof = await noir_programs.recursive.generateProof(recursiveInputs) -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e3c7c1065da..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,231 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo codegen-verifier -``` - -A new `contract` folder would then be generated in your project directory, containing the Solidity -file `plonk_vk.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. For `_proof`, run `nargo prove` and use the string in `proof/.proof` (adding the hex `0x` prefix). We can also copy the public input from `Verifier.toml`, as it will be properly formatted as 32-byte strings: - -``` -0x...... , [0x0000.....02] -``` - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in -Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of -the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. Like before, these values are populated in Verifier.toml after running `nargo prove`. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return]`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -ZK-SNARK verification depends on some precompiled cryptographic primitives such as Elliptic Curve Pairings (if you like complex math, you can read about EC Pairings [here](https://medium.com/@VitalikButerin/exploring-elliptic-curve-pairings-c73c1864e627)). Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/merkle-proof.mdx deleted file mode 100644 index 16c425bed76..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,49 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] -sidebar_position: 4 ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust -use dep::std; - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/index.mdx deleted file mode 100644 index 75086ddcdde..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is a Domain-Specific Language for SNARK proving systems developed by [Aztec Labs](https://aztec.network/). It allows you to generate complex Zero-Knowledge Programs (ZKP) by using simple and flexible syntax, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of a certain statement without revealing some details about it. You can read more about ZKPs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 7211716f63e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for -> `false` in _Verifier.toml_. - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/integers.md deleted file mode 100644 index 6b2d3773912..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,157 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. -The Noir frontend supports both unsigned and signed integer types. -The allowed sizes are 1, 8, 16, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo prove -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust -use dep::std; - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index 4eccc677b80..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,195 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -use dep::std::slice; - -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` - -### as_array - -Converts this slice into an array. - -Make sure to specify the size of the resulting array. -Panics if the resulting array length is different than the slice's length. - -```rust -fn as_array(self) -> [T; N] -``` - -Example: - -```rust -fn main() { - let slice = &[5, 6]; - - // Always specify the length of the resulting array! - let array: [Field; 2] = slice.as_array(); - - assert(array[0] == slice[0]); - assert(array[1] == slice[1]); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 8ab5825a4c4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,80 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust -use dep::std; - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/functions.md deleted file mode 100644 index f656cdfd97a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/ops.md deleted file mode 100644 index c35c36c38a9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer, shift must be u8 | -| >> | Right shift an integer by another integer amount | Types must be integer, shift must be u8 | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/oracles.md deleted file mode 100644 index aa380b5f7b8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/oracles.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -:::note - -This is an experimental feature that is not fully documented. If you notice any outdated information or potential improvements to this page, pull request contributions are very welcome: https://github.com/noir-lang/noir - -::: - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` - -The timeout for when using an external RPC oracle resolver can be set with the `NARGO_FOREIGN_CALL_TIMEOUT` environment variable. This timeout is in units of milliseconds. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/traits.md deleted file mode 100644 index ef1445a5907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: dep::some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: dep::some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 2c028d85853..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use dep::ecrecover; -use dep::lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use dep::std::hash::sha256; -use dep::std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use dep::phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bigint.md deleted file mode 100644 index 2bfdeec6631..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L14-L19 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L70-L78 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - // Construct a big integer from a slice of bytes - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - // Construct a big integer from an array of 32 bytes - let a = Secpk1Fq::from_le_bytes_32([1;32]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index d5694250f05..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [AES128](./cryptographic_primitives/ciphers.mdx#aes128) -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Embedded curve operations (MSM, addition, ...)](./cryptographic_primitives/embedded_curve_ops.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index c22fe8c5045..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,340 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(mut self: Self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L68-L76 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L81-L93 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L98-L113 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L118-L124 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L129-L136 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L141-L148 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L153-L162 - - -### from_array - -```rust -pub fn from_array(array: [T; Len]) -> Self -``` - -Creates a new vector, populating it with values derived from an array input. -The maximum length of the vector is determined based on the type signature. - -Example: -```rust -let bounded_vec: BoundedVec = BoundedVec::from_array([1, 2, 3]) -``` - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L229-L235 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 47faa99aba6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,570 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a poseidon2 hasher -use dep::std::hash::poseidon2::Poseidon2Hasher; -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u64 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index fcfd7e07aa0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,151 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ciphers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ciphers.mdx deleted file mode 100644 index e83e26efb97..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ciphers.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Ciphers -description: - Learn about the implemented ciphers ready to use for any Noir project -keywords: - [ciphers, Noir project, aes128, encrypt] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## aes128 - -Given a plaintext as an array of bytes, returns the corresponding aes128 ciphertext (CBC mode). Input padding is automatically performed using PKCS#7, so that the output length is `input.len() + (16 - input.len() % 16)`. - -```rust title="aes128" showLineNumbers -pub fn aes128_encrypt(input: [u8; N], iv: [u8; 16], key: [u8; 16]) -> [u8] {} -``` -> Source code: noir_stdlib/src/aes128.nr#L2-L4 - - -```rust -fn main() { - let input: [u8; 4] = [0, 12, 3, 15] // Random bytes, will be padded to 16 bytes. - let iv: [u8; 16] = [0; 16]; // Initialisation vector - let key: [u8; 16] = [0; 16] // AES key - let ciphertext = std::aes128::aes128_encrypt(inputs.as_bytes(), iv.as_bytes(), key.as_bytes()); // In this case, the output length will be 16 bytes. -} -``` - - - \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index 8f9f47ce7d0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/v0.30.0/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/v0.30.0/noir_stdlib/src/ec.nr). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use dep::std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index c2c0624dfad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify_with_hasher` function with a parameter implementing the Hasher trait. For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use dep::std::hash::poseidon2::Poseidon2Hasher; - -let mut hasher = Poseidon2Hasher::default(); -eddsa_verify_with_hasher(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg, &mut hasher); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx deleted file mode 100644 index 9dab7dd1047..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplication in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -The following functions perform operations over the embedded curve whose coordinates are defined by the configured noir field. -For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -:::note -Suffixes `_low` and `_high` denote low and high limbs of a scalar. -::: - -## embedded_curve_ops::multi_scalar_mul - -Performs multi scalar multiplication over the embedded curve. -The function accepts arbitrary amount of point-scalar pairs on the input, it multiplies the individual pairs over -the curve and returns a sum of the resulting points. - -Points represented as x and y coordinates [x1, y1, x2, y2, ...], scalars as low and high limbs [low1, high1, low2, high2, ...]. - -```rust title="multi_scalar_mul" showLineNumbers -pub fn multi_scalar_mul( - points: [Field; N], // points represented as x and y coordinates [x1, y1, x2, y2, ...] - scalars: [Field; N] // scalars represented as low and high limbs [low1, high1, low2, high2, ...] -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L43-L48 - - -example - -```rust -fn main(point_x: Field, point_y: Field, scalar_low: Field, scalar_high: Field) { - let point = std::embedded_curve_ops::multi_scalar_mul([point_x, point_y], [scalar_low, scalar_high]); - println(point); -} -``` - -## embedded_curve_ops::fixed_base_scalar_mul - -Performs fixed base scalar multiplication over the embedded curve (multiplies input scalar with a generator point). -The function accepts a single scalar on the input represented as 2 fields. - -```rust title="fixed_base_scalar_mul" showLineNumbers -pub fn fixed_base_scalar_mul( - scalar_low: Field, - scalar_high: Field -) -> [Field; 2] -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L51-L56 - - -example - -```rust -fn main(scalar_low: Field, scalar_high: Field) { - let point = std::embedded_curve_ops::fixed_base_scalar_mul(scalar_low, scalar_high); - println(point); -} -``` - -## embedded_curve_ops::embedded_curve_add - -Adds two points on the embedded curve. -This function takes two `EmbeddedCurvePoint` structures as parameters, representing points on the curve, and returns a new `EmbeddedCurvePoint` structure that represents their sum. - -### Parameters: -- `point1` (`EmbeddedCurvePoint`): The first point to add. -- `point2` (`EmbeddedCurvePoint`): The second point to add. - -### Returns: -- `EmbeddedCurvePoint`: The resulting point after the addition of `point1` and `point2`. - -```rust title="embedded_curve_add" showLineNumbers -fn embedded_curve_add( - point1: EmbeddedCurvePoint, - point2: EmbeddedCurvePoint -) -> EmbeddedCurvePoint -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L65-L70 - - -example - -```rust -fn main() { - let point1 = EmbeddedCurvePoint { x: 1, y: 2 }; - let point2 = EmbeddedCurvePoint { x: 3, y: 4 }; - let result = std::embedded_curve_ops::embedded_curve_add(point1, point2); - println!("Resulting Point: ({}, {})", result.x, result.y); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 3b83d9ec31a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,257 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. -Specify a message_size to hash only the first `message_size` bytes of the input. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L10-L12 - - -example: -```rust title="sha256_var" showLineNumbers -let digest = std::hash::sha256_var([x as u8], 1); -``` -> Source code: test_programs/execution_success/sha256/src/main.nr#L17-L19 - - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::sha256::sha256_var(x, 4); -} -``` - - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L16-L18 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L22-L24 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L46-L48 - - -example: - -```rust title="pedersen-hash" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L8 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -struct PedersenPoint { - x : Field, - y : Field, -} - -pub fn pedersen_commitment(input: [Field; N]) -> PedersenPoint { -``` -> Source code: noir_stdlib/src/hash.nr#L27-L34 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -use dep::std; - -fn main(x: Field, y: Field, expected_commitment: std::hash::PedersenPoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L9 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L68-L70 - - -example: - -```rust title="keccak256" showLineNumbers -use dep::std; - -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L22 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use dep::std::hash::poseidon; -use dep::std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/recursion.md deleted file mode 100644 index f33c285cf4e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,88 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - -:::info - -This is a black box function. Read [this section](./black_box_fns.md) to learn more about black box functions in Noir. - -::: - -## Example usage - -```rust -use dep::std; - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/traits.md deleted file mode 100644 index a14312d2792..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/traits.md +++ /dev/null @@ -1,464 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(self) -> T; -} - -impl Into for U where T: From { - fn into(self) -> T { - T::from(self) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -`std::cmp` also provides `max` and `min` functions for any type which implements the `Ord` trait. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L19-L23 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L37-L41 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L55-L59 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L73-L77 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::Neg` - -```rust title="neg-trait" showLineNumbers -trait Neg { - fn neg(self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L89-L93 - - -`Neg::neg` is equivalent to the unary negation operator `-`. - -Implementations: -```rust title="neg-trait-impls" showLineNumbers -impl Neg for Field { fn neg(self) -> Field { -self } } - -impl Neg for i8 { fn neg(self) -> i8 { -self } } -impl Neg for i16 { fn neg(self) -> i16 { -self } } -impl Neg for i32 { fn neg(self) -> i32 { -self } } -impl Neg for i64 { fn neg(self) -> i64 { -self } } -``` -> Source code: noir_stdlib/src/ops/arith.nr#L95-L102 - - -### `std::ops::Not` - -```rust title="not-trait" showLineNumbers -trait Not { - fn not(self: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L1-L5 - - -`Not::not` is equivalent to the unary bitwise NOT operator `!`. - -Implementations: -```rust title="not-trait-impls" showLineNumbers -impl Not for bool { fn not(self) -> bool { !self } } - -impl Not for u64 { fn not(self) -> u64 { !self } } -impl Not for u32 { fn not(self) -> u32 { !self } } -impl Not for u16 { fn not(self) -> u16 { !self } } -impl Not for u8 { fn not(self) -> u8 { !self } } -impl Not for u1 { fn not(self) -> u1 { !self } } - -impl Not for i8 { fn not(self) -> i8 { !self } } -impl Not for i16 { fn not(self) -> i16 { !self } } -impl Not for i32 { fn not(self) -> i32 { !self } } -impl Not for i64 { fn not(self) -> i64 { !self } } -``` -> Source code: noir_stdlib/src/ops/bit.nr#L7-L20 - - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L22-L26 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L40-L44 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L58-L62 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L76-L80 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L93-L97 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index d7249d24330..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,160 +0,0 @@ -# BarretenbergBackend - -## Extends - -- `BarretenbergVerifierBackend` - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -#### Inherited from - -BarretenbergVerifierBackend.constructor - -## Properties - -| Property | Type | Description | Inheritance | -| :------ | :------ | :------ | :------ | -| `acirComposer` | `any` | - | BarretenbergVerifierBackend.acirComposer | -| `acirUncompressedBytecode` | `Uint8Array` | - | BarretenbergVerifierBackend.acirUncompressedBytecode | -| `api` | `Barretenberg` | - | BarretenbergVerifierBackend.api | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - | BarretenbergVerifierBackend.options | - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Inherited from - -BarretenbergVerifierBackend.destroy - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### getVerificationKey() - -```ts -getVerificationKey(): Promise -``` - -#### Returns - -`Promise`\<`Uint8Array`\> - -#### Inherited from - -BarretenbergVerifierBackend.getVerificationKey - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Inherited from - -BarretenbergVerifierBackend.verifyProof - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md deleted file mode 100644 index 500276ea748..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md +++ /dev/null @@ -1,58 +0,0 @@ -# BarretenbergVerifier - -## Constructors - -### new BarretenbergVerifier(options) - -```ts -new BarretenbergVerifier(options): BarretenbergVerifier -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergVerifier`](BarretenbergVerifier.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### verifyProof() - -```ts -verifyProof(proofData, verificationKey): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | -| `verificationKey` | `Uint8Array` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index 64971973196..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,59 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | -| [BarretenbergVerifier](classes/BarretenbergVerifier.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -## Functions - -### publicInputsToWitnessMap() - -```ts -publicInputsToWitnessMap(publicInputs, abi): Backend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `publicInputs` | `string`[] | -| `abi` | `Abi` | - -#### Returns - -[`Backend`](index.md#backend) - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index d7d5128f9e3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier","label":"BarretenbergVerifier"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index 45dd62ee57e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,132 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit, backend) - -```ts -new Noir(circuit, backend?): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | -| `backend`? | `any` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Description - -Destroys the underlying backend instance. - -#### Example - -```typescript -await noir.destroy(); -``` - -*** - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -### generateProof() - -```ts -generateProof(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a witness and a proof given an object as input. - -#### Example - -```typescript -async generateProof(input) -``` - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Instantiates the verification key and verifies a proof. - -#### Example - -```typescript -async verifyProof(proof) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index 40bef8393fc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,55 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ErrorWithPayload](type-aliases/ErrorWithPayload.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -*** - -### ProofData - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md deleted file mode 100644 index e8c2f4aef3d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md +++ /dev/null @@ -1,15 +0,0 @@ -# ErrorWithPayload - -```ts -type ErrorWithPayload: ExecutionError & object; -``` - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `decodedAssertionPayload` | `any` | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index b3156097df6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ErrorWithPayload","label":"ErrorWithPayload"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/_category_.json deleted file mode 100644 index 27869205ad3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugger", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_known_limitations.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_known_limitations.md deleted file mode 100644 index 936d416ac4b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_known_limitations.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Known limitations -description: - An overview of known limitations of the current version of the Noir debugger -keywords: - [ - Nargo, - Noir Debugger, - VS Code, - ] -sidebar_position: 2 ---- - -# Debugger Known Limitations - -There are currently some limits to what the debugger can observe. - -## Mutable references - -The debugger is currently blind to any state mutated via a mutable reference. For example, in: - -``` -let mut x = 1; -let y = &mut x; -*y = 2; -``` - -The update on `x` will not be observed by the debugger. That means, when running `vars` from the debugger REPL, or inspecting the _local variables_ pane in the VS Code debugger, `x` will appear with value 1 despite having executed `*y = 2;`. - -## Variables of type function or mutable references are opaque - -When inspecting variables, any variable of type `Function` or `MutableReference` will render its value as `<>` or `<>`. - -## Debugger instrumentation affects resulting ACIR - -In order to make the state of local variables observable, the debugger compiles Noir circuits interleaving foreign calls that track any mutations to them. While this works (except in the cases described above) and doesn't introduce any behavior changes, it does as a side effect produce bigger bytecode. In particular, when running the command `opcodes` on the REPL debugger, you will notice Unconstrained VM blocks that look like this: - -``` -... -5 BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [], q_c: 2 }), Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(2))], q_c: 0 })] - | outputs=[] - 5.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 5.1 | Mov { destination: RegisterIndex(3), source: RegisterIndex(1) } - 5.2 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 5.3 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 5.4 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 5.5 | Mov { destination: RegisterIndex(3), source: RegisterIndex(3) } - 5.6 | Call { location: 8 } - 5.7 | Stop - 5.8 | ForeignCall { function: "__debug_var_assign", destinations: [], inputs: [RegisterIndex(RegisterIndex(2)), RegisterIndex(RegisterIndex(3))] } -... -``` - -If you are interested in debugging/inspecting compiled ACIR without these synthetic changes, you can invoke the REPL debugger with the `--skip-instrumentation` flag or launch the VS Code debugger with the `skipConfiguration` property set to true in its launch configuration. You can find more details about those in the [Debugger REPL reference](debugger_repl.md) and the [VS Code Debugger reference](debugger_vscode.md). - -:::note -Skipping debugger instrumentation means you won't be able to inspect values of local variables. -::: - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_repl.md deleted file mode 100644 index 46e2011304e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_repl.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: REPL Debugger -description: - Noir Debugger REPL options and commands. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -## Running the REPL debugger - -`nargo debug [OPTIONS] [WITNESS_NAME]` - -Runs the Noir REPL debugger. If a `WITNESS_NAME` is provided the debugger writes the resulting execution witness to a `WITNESS_NAME` file. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover]| -| `--package ` | The name of the package to debug | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -None of these options are required. - -:::note -Since the debugger starts by compiling the target package, all Noir compiler options are also available. Check out the [compiler reference](../nargo_commands.md#nargo-compile) to learn more about the compiler options. -::: - -## REPL commands - -Once the debugger is running, it accepts the following commands. - -#### `help` (h) - -Displays the menu of available commands. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) value - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -### Stepping through programs - -#### `next` (n) - -Step until the next Noir source code location. While other commands, such as [`into`](#into-i) and [`step`](#step-s), allow for finer grained control of the program's execution at the opcode level, `next` is source code centric. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `next` here would cause the debugger to jump to the definition of `deep_entry_point` (if available). - -If you want to step over `deep_entry_point` and go straight to line 8, use [the `over` command](#over) instead. - -#### `over` - -Step until the next source code location, without diving into function calls. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `over` here would cause the debugger to execute until line 8 (`multiple_values_entry_point(x);`). - -If you want to step into `deep_entry_point` instead, use [the `next` command](#next-n). - -#### `out` - -Step until the end of the current function call. For example: - -``` - 3 ... - 4 fn main(x: u32) { - 5 assert(entry_point(x) == 2); - 6 swap_entry_point(x, x + 1); - 7 -> assert(deep_entry_point(x) == 4); - 8 multiple_values_entry_point(x); - 9 } - 10 - 11 unconstrained fn returns_multiple_values(x: u32) -> (u32, u32, u32, u32) { - 12 ... - ... - 55 - 56 unconstrained fn deep_entry_point(x: u32) -> u32 { - 57 -> level_1(x + 1) - 58 } - -``` - -Running `out` here will resume execution until line 8. - -#### `step` (s) - -Skips to the next ACIR code. A compiled Noir program is a sequence of ACIR opcodes. However, an unconstrained VM opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `step` command at this point would result in the debugger stopping at ACIR opcode 2, `EXPR`, skipping unconstrained computation steps. - -Use [the `into` command](#into-i) instead if you want to follow unconstrained computation step by step. - -#### `into` (i) - -Steps into the next opcode. A compiled Noir program is a sequence of ACIR opcodes. However, a BRILLIG opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `into` command at this point would result in the debugger stopping at opcode 1.0, `Mov ...`, allowing the debugger user to follow unconstrained computation step by step. - -Use [the `step` command](#step-s) instead if you want to skip to the next ACIR code directly. - -#### `continue` (c) - -Continues execution until the next breakpoint, or the end of the program. - -#### `restart` (res) - -Interrupts execution, and restarts a new debugging session from scratch. - -#### `opcodes` (o) - -Display the program's ACIR opcode sequence. For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -### Breakpoints - -#### `break [Opcode]` (or shorthand `b [Opcode]`) - -Sets a breakpoint on the specified opcode index. To get a list of the program opcode numbers, see [the `opcode` command](#opcodes-o). For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -In this example, issuing a `break 1.2` command adds break on opcode 1.2, as denoted by the `*` character: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | * Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -Running [the `continue` command](#continue-c) at this point would cause the debugger to execute the program until opcode 1.2. - -#### `delete [Opcode]` (or shorthand `d [Opcode]`) - -Deletes a breakpoint at an opcode location. Usage is analogous to [the `break` command](#). - -### Variable inspection - -#### vars - -Show variable values available at this point in execution. - -:::note -The ability to inspect variable values from the debugger depends on compilation to be run in a special debug instrumentation mode. This instrumentation weaves variable tracing code with the original source code. - -So variable value inspection comes at the expense of making the resulting ACIR bytecode bigger and harder to understand and optimize. - -If you find this compromise unacceptable, you can run the debugger with the flag `--skip-debug-instrumentation`. This will compile your circuit without any additional debug information, so the resulting ACIR bytecode will be identical to the one produced by standard Noir compilation. However, if you opt for this, the `vars` command will not be available while debugging. -::: - - -### Stacktrace - -#### `stacktrace` - -Displays the current stack trace. - - -### Witness map - -#### `witness` (w) - -Show witness map. For example: - -``` -_0 = 0 -_1 = 2 -_2 = 1 -``` - -#### `witness [Witness Index]` - -Display a single witness from the witness map. For example: - -``` -> witness 1 -_1 = 2 -``` - -#### `witness [Witness Index] [New value]` - -Overwrite the given index with a new value. For example: - -``` -> witness 1 3 -_1 = 3 -``` - - -### Unconstrained VM memory - -#### `memory` - -Show unconstrained VM memory state. For example: - -``` -> memory -At opcode 1.13: Store { destination_pointer: RegisterIndex(0), source: RegisterIndex(3) } -... -> registers -0 = 0 -1 = 10 -2 = 0 -3 = 1 -4 = 1 -5 = 2³² -6 = 1 -> into -At opcode 1.14: Const { destination: RegisterIndex(5), value: Value { inner: 1 } } -... -> memory -0 = 1 -> -``` - -In the example above: we start with clean memory, then step through a `Store` opcode which stores the value of register 3 (1) into the memory address stored in register 0 (0). Thus now `memory` shows memory address 0 contains value 1. - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: - -#### `memset [Memory address] [New value]` - -Update a memory cell with the given value. For example: - -``` -> memory -0 = 1 -> memset 0 2 -> memory -0 = 2 -> memset 1 4 -> memory -0 = 2 -1 = 4 -> -``` - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_vscode.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_vscode.md deleted file mode 100644 index c027332b3b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/debugger/debugger_vscode.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: VS Code Debugger -description: - VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -# VS Code Noir Debugger Reference - -The Noir debugger enabled by the vscode-noir extension ships with default settings such that the most common scenario should run without any additional configuration steps. - -These defaults can nevertheless be overridden by defining a launch configuration file. This page provides a reference for the properties you can override via a launch configuration file, as well as documenting the Nargo `dap` command, which is a dependency of the VS Code Noir debugger. - - -## Creating and editing launch configuration files - -To create a launch configuration file from VS Code, open the _debug pane_, and click on _create a launch.json file_. - -![Creating a launch configuration file](@site/static/img/debugger/ref1-create-launch.png) - -A `launch.json` file will be created, populated with basic defaults. - -### Noir Debugger launch.json properties - -#### projectFolder - -_String, optional._ - -Absolute path to the Nargo project to debug. By default, it is dynamically determined by looking for the nearest `Nargo.toml` file to the active file at the moment of launching the debugger. - -#### proverName - -_String, optional._ - -Name of the prover input to use. Defaults to `Prover`, which looks for a file named `Prover.toml` at the `projectFolder`. - -#### generateAcir - -_Boolean, optional._ - -If true, generate ACIR opcodes instead of unconstrained opcodes which will be closer to release binaries but less convenient for debugging. Defaults to `false`. - -#### skipInstrumentation - -_Boolean, optional._ - -Skips variables debugging instrumentation of code, making debugging less convenient but the resulting binary smaller and closer to production. Defaults to `false`. - -:::note -Skipping instrumentation causes the debugger to be unable to inspect local variables. -::: - -## `nargo dap [OPTIONS]` - -When run without any option flags, it starts the Nargo Debug Adapter Protocol server, which acts as the debugging backend for the VS Code Noir Debugger. - -All option flags are related to preflight checks. The Debug Adapter Protocol specifies how errors are to be informed from a running DAP server, but it doesn't specify mechanisms to communicate server initialization errors between the DAP server and its client IDE. - -Thus `nargo dap` ships with a _preflight check_ mode. If flag `--preflight-check` and the rest of the `--preflight-*` flags are provided, Nargo will run the same initialization routine except it will not start the DAP server. - -`vscode-noir` will then run `nargo dap` in preflight check mode first before a debugging session starts. If the preflight check ends in error, vscode-noir will present stderr and stdout output from this process through its own Output pane in VS Code. This makes it possible for users to diagnose what pieces of configuration might be wrong or missing in case of initialization errors. - -If the preflight check succeeds, `vscode-noir` proceeds to start the DAP server normally but running `nargo dap` without any additional flags. - -### Options - -| Option | Description | -| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `--preflight-check` | If present, dap runs in preflight check mode. | -| `--preflight-project-folder ` | Absolute path to the project to debug for preflight check. | -| `--preflight-prover-name ` | Name of prover file to use for preflight check | -| `--preflight-generate-acir` | Optional. If present, compile in ACIR mode while running preflight check. | -| `--preflight-skip-instrumentation` | Optional. If present, compile without introducing debug instrumentation while running preflight check. | -| `-h, --help` | Print help. | diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/nargo_commands.md deleted file mode 100644 index 519e3dbddc2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/reference/nargo_commands.md +++ /dev/null @@ -1,397 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo backend`↴](#nargo-backend) -* [`nargo backend current`↴](#nargo-backend-current) -* [`nargo backend ls`↴](#nargo-backend-ls) -* [`nargo backend use`↴](#nargo-backend-use) -* [`nargo backend install`↴](#nargo-backend-install) -* [`nargo backend uninstall`↴](#nargo-backend-uninstall) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo codegen-verifier`↴](#nargo-codegen-verifier) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo prove`↴](#nargo-prove) -* [`nargo verify`↴](#nargo-verify) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `backend` — Install and select custom backends used to generate and verify proofs -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `codegen-verifier` — Generates a Solidity verifier smart contract for the program -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `prove` — Create proof for this program. The proof is returned as a hex encoded string -* `verify` — Given a proof and a program, verify whether the proof is valid -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo backend` - -Install and select custom backends used to generate and verify proofs - -**Usage:** `nargo backend ` - -###### **Subcommands:** - -* `current` — Prints the name of the currently active backend -* `ls` — Prints the list of currently installed backends -* `use` — Select the backend to use -* `install` — Install a new backend from a URL -* `uninstall` — Uninstalls a backend - - - -## `nargo backend current` - -Prints the name of the currently active backend - -**Usage:** `nargo backend current` - - - -## `nargo backend ls` - -Prints the list of currently installed backends - -**Usage:** `nargo backend ls` - - - -## `nargo backend use` - -Select the backend to use - -**Usage:** `nargo backend use ` - -###### **Arguments:** - -* `` - - - -## `nargo backend install` - -Install a new backend from a URL - -**Usage:** `nargo backend install ` - -###### **Arguments:** - -* `` — The name of the backend to install -* `` — The URL from which to download the backend - - - -## `nargo backend uninstall` - -Uninstalls a backend - -**Usage:** `nargo backend uninstall ` - -###### **Arguments:** - -* `` — The name of the backend to uninstall - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo codegen-verifier` - -Generates a Solidity verifier smart contract for the program - -**Usage:** `nargo codegen-verifier [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to codegen -* `--workspace` — Codegen all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo prove` - -Create proof for this program. The proof is returned as a hex encoded string - -**Usage:** `nargo prove [OPTIONS]` - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--verify` — Verify proof after proving -* `--package ` — The name of the package to prove -* `--workspace` — Prove all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo verify` - -Given a proof and a program, verify whether the proof is valid - -**Usage:** `nargo verify [OPTIONS]` - -###### **Options:** - -* `-v`, `--verifier-name ` — The name of the toml file which contains the inputs for the verifier - - Default value: `Verifier` -* `--package ` — The name of the package verify -* `--workspace` — Verify all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/debugger.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/debugger.md deleted file mode 100644 index 9b7565ba9ff..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/debugger.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Debugger -description: Learn about the Noir Debugger, in its REPL or VS Code versions. -keywords: [Nargo, VSCode, Visual Studio Code, REPL, Debugger] -sidebar_position: 2 ---- - -# Noir Debugger - -There are currently two ways of debugging Noir programs: - -1. From VS Code, via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). -2. Via the REPL debugger, which ships with Nargo. - -In order to use either version of the debugger, you will need to install recent enough versions of Noir, [Nargo](../getting_started/installation/index.md) and vscode-noir: - -- Noir & Nargo ≥0.28.0 -- Noir's VS Code extension ≥0.0.11 - -:::info -At the moment, the debugger supports debugging binary projects, but not contracts. -::: - -We cover the VS Code Noir debugger more in depth in [its VS Code debugger how-to guide](../how_to/debugger/debugging_with_vs_code.md) and [the reference](../reference/debugger/debugger_vscode.md). - -The REPL debugger is discussed at length in [the REPL debugger how-to guide](../how_to/debugger/debugging_with_the_repl.md) and [the reference](../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tutorials/noirjs_app.md deleted file mode 100644 index 3dd9fe7d2b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.30.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,326 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.27.x matches `noir_js@0.27.x`, etc. - -In this guide, we will be pinned to 0.27.0. - -::: - -Before we start, we want to make sure we have Node and Nargo installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -`nargo new circuit` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -`nargo compile` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from "vite"; -import copy from "rollup-plugin-copy"; - -export default defineConfig({ - esbuild: { - target: "esnext", - }, - optimizeDeps: { - esbuildOptions: { - target: "esnext", - }, - }, - plugins: [ - copy({ - targets: [ - { src: "node_modules/**/*.wasm", dest: "node_modules/.vite/dist" }, - ], - copySync: true, - hook: "buildStart", - }), - ], - server: { - port: 3000, - }, -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.27.0 @noir-lang/noir_js@0.27.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -const setup = async () => { - await Promise.all([ - import('@noir-lang/noirc_abi').then((module) => - module.default(new URL('@noir-lang/noirc_abi/web/noirc_abi_wasm_bg.wasm', import.meta.url).toString()), - ), - import('@noir-lang/acvm_js').then((module) => - module.default(new URL('@noir-lang/acvm_js/web/acvm_js_bg.wasm', import.meta.url).toString()), - ), - ]); -}; - -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -As for the `setup` function, it's just a sad reminder that dealing with `wasm` on the browser is not as easy as it should. Just copy, paste, and forget. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend, BarretenbergVerifier as Verifier } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit, backend); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const proof = await noir.generateProof(input); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const verificationKey = await backend.getVerificationKey(); -const verifier = new Verifier(); -const isValid = await verifier.verifyProof(proof, verificationKey); -if (isValid) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-oracle.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-oracle.md deleted file mode 100644 index b84ca5dd986..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-oracle.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -title: Oracles -description: This guide provides an in-depth understanding of how Oracles work in Noir programming. Learn how to use outside calculations in your programs, constrain oracles, and understand their uses and limitations. -keywords: - - Noir Programming - - Oracles - - JSON-RPC - - Foreign Call Handlers - - Constrained Functions - - Blockchain Programming -sidebar_position: 1 ---- - -If you've seen "The Matrix" you may recall "The Oracle" as Gloria Foster smoking cigarettes and baking cookies. While she appears to "know things", she is actually providing a calculation of a pre-determined future. Noir Oracles are similar, in a way. They don't calculate the future (yet), but they allow you to use outside calculations in your programs. - -![matrix oracle prediction](@site/static/img/memes/matrix_oracle.jpeg) - -A Noir program is usually self-contained. You can pass certain inputs to it, and it will generate a deterministic output for those inputs. But what if you wanted to defer some calculation to an outside process or source? - -Oracles are functions that provide this feature. - -## Use cases - -An example usage for Oracles is proving something on-chain. For example, proving that the ETH-USDC quote was below a certain target at a certain block time. Or even making more complex proofs like proving the ownership of an NFT as an anonymous login method. - -Another interesting use case is to defer expensive calculations to be made outside of the Noir program, and then constraining the result; similar to the use of [unconstrained functions](../noir/concepts//unconstrained.md). - -In short, anything that can be constrained in a Noir program but needs to be fetched from an external source is a great candidate to be used in oracles. - -## Constraining oracles - -Just like in The Matrix, Oracles are powerful. But with great power, comes great responsibility. Just because you're using them in a Noir program doesn't mean they're true. Noir has no superpowers. If you want to prove that Portugal won the Euro Cup 2016, you're still relying on potentially untrusted information. - -To give a concrete example, Alice wants to login to the [NounsDAO](https://nouns.wtf/) forum with her username "noir_nouner" by proving she owns a noun without revealing her ethereum address. Her Noir program could have a oracle call like this: - -```rust -#[oracle(getNoun)] -unconstrained fn get_noun(address: Field) -> Field -``` - -This oracle could naively resolve with the number of Nouns she possesses. However, it is useless as a trusted source, as the oracle could resolve to anything Alice wants. In order to make this oracle call actually useful, Alice would need to constrain the response from the oracle, by proving her address and the noun count belongs to the state tree of the contract. - -In short, **Oracles don't prove anything. Your Noir program does.** - -:::danger - -If you don't constrain the return of your oracle, you could be clearly opening an attack vector on your Noir program. Make double-triple sure that the return of an oracle call is constrained! - -::: - -## How to use Oracles - -On CLI, Nargo resolves oracles by making JSON RPC calls, which means it would require an RPC node to be running. - -In JavaScript, NoirJS accepts and resolves arbitrary call handlers (that is, not limited to JSON) as long as they matches the expected types the developer defines. Refer to [Foreign Call Handler](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) to learn more about NoirJS's call handling. - -If you want to build using oracles, follow through to the [oracle guide](../how_to/how-to-oracles.md) for a simple example on how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-recursion.md deleted file mode 100644 index 18846176ca7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/explainers/explainer-recursion.md +++ /dev/null @@ -1,176 +0,0 @@ ---- -title: Recursive proofs -description: Explore the concept of recursive proofs in Zero-Knowledge programming. Understand how recursion works in Noir, a language for writing smart contracts on the EVM blockchain. Learn through practical examples like Alice and Bob's guessing game, Charlie's recursive merkle tree, and Daniel's reusable components. Discover how to use recursive proofs to optimize computational resources and improve efficiency. - -keywords: - [ - "Recursive Proofs", - "Zero-Knowledge Programming", - "Noir", - "EVM Blockchain", - "Smart Contracts", - "Recursion in Noir", - "Alice and Bob Guessing Game", - "Recursive Merkle Tree", - "Reusable Components", - "Optimizing Computational Resources", - "Improving Efficiency", - "Verification Key", - "Aggregation", - "Recursive zkSNARK schemes", - "PLONK", - "Proving and Verification Keys" - ] -sidebar_position: 1 -pagination_next: how_to/how-to-recursion ---- - -In programming, we tend to think of recursion as something calling itself. A classic example would be the calculation of the factorial of a number: - -```js -function factorial(n) { - if (n === 0 || n === 1) { - return 1; - } else { - return n * factorial(n - 1); - } -} -``` - -In this case, while `n` is not `1`, this function will keep calling itself until it hits the base case, bubbling up the result on the call stack: - -```md - Is `n` 1? <--------- - /\ / - / \ n = n -1 - / \ / - Yes No -------- -``` - -In Zero-Knowledge, recursion has some similarities. - -It is not a Noir function calling itself, but a proof being used as an input to another circuit. In short, you verify one proof *inside* another proof, returning the proof that both proofs are valid. - -This means that, given enough computational resources, you can prove the correctness of any arbitrary number of proofs in a single proof. This could be useful to design state channels (for which a common example would be [Bitcoin's Lightning Network](https://en.wikipedia.org/wiki/Lightning_Network)), to save on gas costs by settling one proof on-chain, or simply to make business logic less dependent on a consensus mechanism. - -## Examples - -Let us look at some of these examples - -### Alice and Bob - Guessing game - -Alice and Bob are friends, and they like guessing games. They want to play a guessing game online, but for that, they need a trusted third-party that knows both of their secrets and finishes the game once someone wins. - -So, they use zero-knowledge proofs. Alice tries to guess Bob's number, and Bob will generate a ZK proof stating whether she succeeded or failed. - -This ZK proof can go on a smart contract, revealing the winner and even giving prizes. However, this means every turn needs to be verified on-chain. This incurs some cost and waiting time that may simply make the game too expensive or time-consuming to be worth it. - -As a solution, Alice proposes the following: "what if Bob generates his proof, and instead of sending it on-chain, I verify it *within* my own proof before playing my own turn?". - -She can then generate a proof that she verified his proof, and so on. - -```md - Did you fail? <-------------------------- - / \ / - / \ n = n -1 - / \ / - Yes No / - | | / - | | / - | You win / - | / - | / -Generate proof of that / - + / - my own guess ---------------- -``` - -### Charlie - Recursive merkle tree - -Charlie is a concerned citizen, and wants to be sure his vote in an election is accounted for. He votes with a ZK proof, but he has no way of knowing that his ZK proof was included in the total vote count! - -If the vote collector puts all of the votes into a [Merkle tree](https://en.wikipedia.org/wiki/Merkle_tree), everyone can prove the verification of two proofs within one proof, as such: - -```md - abcd - __________|______________ - | | - ab cd - _____|_____ ______|______ - | | | | - alice bob charlie daniel -``` - -Doing this recursively allows us to arrive on a final proof `abcd` which if true, verifies the correctness of all the votes. - -### Daniel - Reusable components - -Daniel has a big circuit and a big headache. A part of his circuit is a setup phase that finishes with some assertions that need to be made. But that section alone takes most of the proving time, and is largely independent of the rest of the circuit. - -He might find it more efficient to generate a proof for that setup phase separately, and verify that proof recursively in the actual business logic section of his circuit. This will allow for parallelization of both proofs, which results in a considerable speedup. - -## What params do I need - -As you can see in the [recursion reference](noir/standard_library/recursion.md), a simple recursive proof requires: - -- The proof to verify -- The Verification Key of the circuit that generated the proof -- A hash of this verification key, as it's needed for some backends -- The public inputs for the proof - -:::info - -Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. - -So, taking the example of Alice and Bob and their guessing game: - -- Alice makes her guess. Her proof is *not* recursive: it doesn't verify any proof within it! It's just a standard `assert(x != y)` circuit -- Bob verifies Alice's proof and makes his own guess. In this circuit, he doesn't exactly *prove* the verification of Alice's proof. Instead, he *aggregates* his proof to Alice's proof. The actual verification is done when the full proof is verified, for example when using `nargo verify` or through the verifier smart contract. - -We can imagine recursive proofs a [relay race](https://en.wikipedia.org/wiki/Relay_race). The first runner doesn't have to receive the baton from anyone else, as he/she already starts with it. But when his/her turn is over, the next runner needs to receive it, run a bit more, and pass it along. Even though every runner could theoretically verify the baton mid-run (why not? 🏃🔍), only at the end of the race does the referee verify that the whole race is valid. - -::: - -## Some architecture - -As with everything in computer science, there's no one-size-fits all. But there are some patterns that could help understanding and implementing them. To give three examples: - -### Adding some logic to a proof verification - -This would be an approach for something like our guessing game, where proofs are sent back and forth and are verified by each opponent. This circuit would be divided in two sections: - -- A `recursive verification` section, which would be just the call to `std::verify_proof`, and that would be skipped on the first move (since there's no proof to verify) -- A `guessing` section, which is basically the logic part where the actual guessing happens - -In such a situation, and assuming Alice is first, she would skip the first part and try to guess Bob's number. Bob would then verify her proof on the first section of his run, and try to guess Alice's number on the second part, and so on. - -### Aggregating proofs - -In some one-way interaction situations, recursion would allow for aggregation of simple proofs that don't need to be immediately verified on-chain or elsewhere. - -To give a practical example, a barman wouldn't need to verify a "proof-of-age" on-chain every time he serves alcohol to a customer. Instead, the architecture would comprise two circuits: - -- A `main`, non-recursive circuit with some logic -- A `recursive` circuit meant to verify two proofs in one proof - -The customer's proofs would be intermediate, and made on their phones, and the barman could just verify them locally. He would then aggregate them into a final proof sent on-chain (or elsewhere) at the end of the day. - -### Recursively verifying different circuits - -Nothing prevents you from verifying different circuits in a recursive proof, for example: - -- A `circuit1` circuit -- A `circuit2` circuit -- A `recursive` circuit - -In this example, a regulator could verify that taxes were paid for a specific purchase by aggregating both a `payer` circuit (proving that a purchase was made and taxes were paid), and a `receipt` circuit (proving that the payment was received) - -## How fast is it - -At the time of writing, verifying recursive proofs is surprisingly fast. This is because most of the time is spent on generating the verification key that will be used to generate the next proof. So you are able to cache the verification key and reuse it later. - -Currently, Noir JS packages don't expose the functionality of loading proving and verification keys, but that feature exists in the underlying `bb.js` package. - -## How can I try it - -Learn more about using recursion in Nargo and NoirJS in the [how-to guide](../how_to/how-to-recursion.md) and see a full example in [noir-examples](https://github.com/noir-lang/noir-examples). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/_category_.json deleted file mode 100644 index b82e92beb0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 1, - "label": "Install Proving Backend", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/index.md deleted file mode 100644 index 7192d954877..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/backend/index.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Proving Backend Installation -description: Proving backends offer command line tools for proving and verifying Noir programs. This page describes how to install `bb` as an example. -keywords: [ - Proving - Backend - Barretenberg - bb - bbup - Installation - Terminal - Command - CLI - Version -] -pagination_next: getting_started/hello_noir/index ---- - -Proving backends each provide their own tools for working with Noir programs, providing functionality like proof generation, proof verification, and verifier smart contract generation. - -For the latest information on tooling provided by each proving backend, installation instructions, Noir version compatibility... you may refer to the proving backends' own documentation. - -You can find the full list of proving backends compatible with Noir in [Awesome Noir](https://github.com/noir-lang/awesome-noir/?tab=readme-ov-file#proving-backends). - -## Example: Installing `bb` - -`bb` is the CLI tool provided by the [Barretenberg proving backend](https://github.com/AztecProtocol/barretenberg) developed by Aztec Labs. - -You can find the instructions for installation in [`bb`'s documentation](https://github.com/AztecProtocol/aztec-packages/blob/master/barretenberg/cpp/src/barretenberg/bb/readme.md#installation). - -Once installed, we are ready to start working on [our first Noir program](../hello_noir/index.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/_category_.json deleted file mode 100644 index 976a2325de0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/index.md deleted file mode 100644 index 3baae217eb3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/index.md +++ /dev/null @@ -1,152 +0,0 @@ ---- -title: Creating a Project -description: - Learn how to create and verify your first Noir program using Nargo, a programming language for - zero-knowledge proofs. -keywords: - [ - Nargo, - Noir, - zero-knowledge proofs, - programming language, - create Noir program, - verify Noir program, - step-by-step guide, - ] -sidebar_position: 1 - ---- - -Now that we have installed Nargo and a proving backend, it is time to make our first hello world program! - -### 1. Create a new project directory - -Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home -directory to house our first Noir program. - -Create the directory and change directory into it by running: - -```sh -mkdir ~/projects -cd ~/projects -``` - -## Nargo - -Nargo provides the ability to initiate and execute Noir projects. Read the [Nargo installation](../installation/index.md) section to learn more about Nargo and how to install it. - -### 2. Create a new Noir project - -Now that we are in the projects directory, create a new Nargo project by running: - -```sh -nargo new hello_world -``` - -`hello_world` can be any arbitrary project name, we are simply using `hello_world` for demonstration. - -In production, it is common practice to name the project folder, `circuits`, for clarity amongst other folders in the codebase (like: `contracts`, `scripts`, and `test`). - -A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and -_Nargo.toml_ which contain the source code and environmental options of your Noir program -respectively. - -#### Intro to Noir Syntax - -Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -The first line of the program specifies the program's inputs: - -```rust -x : Field, y : pub Field -``` - -Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the -keyword `pub` (e.g. `y`). To learn more about private and public values, check the -[Data Types](../../noir/concepts/data_types/index.md) section. - -The next line of the program specifies its body: - -```rust -assert(x != y); -``` - -The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. - -For more Noir syntax, check the [Language Concepts](../../noir/concepts/comments.md) chapter. - -### 3. Build in/output files - -Change directory into _hello_world_ and build in/output files for your Noir program by running: - -```sh -cd hello_world -nargo check -``` - -A _Prover.toml_ file will be generated in your project directory, to allow specifying input values to the program. - -### 4. Execute the Noir program - -Now that the project is set up, we can execute our Noir program. - -Fill in input values for execution in the _Prover.toml_ file. For example: - -```toml -x = "1" -y = "2" -``` - -Execute your Noir program: - -```sh -nargo execute witness-name -``` - -The witness corresponding to this execution will then be written to the file `./target/witness-name.gz`. - -The command also automatically compiles your Noir program if it was not already / was edited, which you may notice the compiled artifacts being written to the file `./target/hello_world.json`. - -## Proving Backend - -Proving backends provide the ability to generate and verify proofs of executing Noir programs, following Noir's tooling that compiles and executes the programs. Read the [proving backend installation](../backend/index.md) section to learn more about proving backends and how to install them. - -Barretenberg is used as an example here to demonstrate how proving and verifying could be implemented and used. Read the [`bb` installation](../backend/index.md#example-installing-bb) section for how to install Barretenberg's CLI tool; refer to [`bb`'s documentation](https://github.com/AztecProtocol/aztec-packages/blob/master/barretenberg/cpp/src/barretenberg/bb/readme.md) for full details about the tool. - -### 5. Prove an execution of the Noir program - -Using Barretenberg as an example, prove the valid execution of your Noir program running: - -```sh -bb prove -b ./target/hello_world.json -w ./target/witness-name.gz -o ./target/proof -``` - -The proof generated will then be written to the file `./target/proof`. - -### 6. Verify the execution proof - -Once a proof is generated, we can verify correct execution of our Noir program by verifying the proof file. - -Using Barretenberg as an example, compute the verification key for the Noir program by running: - -```sh -bb write_vk -b ./target/hello_world.json -o ./target/vk -``` - -And verify your proof by running: - -```sh -bb verify -k ./target/vk -p ./target/proof -``` - -If successful, the verification will complete in silence; if unsuccessful, the command will trigger logging of the corresponding error. - -Congratulations, you have now created and verified a proof for your very first Noir program! - -In the [next section](./project_breakdown.md), we will go into more detail on each step performed. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/project_breakdown.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/project_breakdown.md deleted file mode 100644 index 96e653f6c08..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/hello_noir/project_breakdown.md +++ /dev/null @@ -1,159 +0,0 @@ ---- -title: Project Breakdown -description: - Learn about the anatomy of a Nargo project, including the purpose of the Prover TOML - file, and how to prove and verify your program. -keywords: - [Nargo, Nargo project, Prover.toml, proof verification, private asset transfer] -sidebar_position: 2 ---- - -This section breaks down our hello world program from the previous section. - -## Anatomy of a Nargo Project - -Upon creating a new project with `nargo new` and building the in/output files with `nargo check` -commands, you would get a minimal Nargo project of the following structure: - - - src - - Prover.toml - - Nargo.toml - -The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ -file will be generated within it. - -### Prover.toml - -_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. - -### Nargo.toml - -_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. - -Example Nargo.toml: - -```toml -[package] -name = "noir_starter" -type = "bin" -authors = ["Alice"] -compiler_version = "0.9.0" -description = "Getting started with Noir" -entry = "circuit/main.nr" -license = "MIT" - -[dependencies] -ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} -``` - -Nargo.toml for a [workspace](../../noir/modules_packages_crates/workspaces.md) will look a bit different. For example: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -#### Package section - -The package section defines a number of fields including: - -- `name` (**required**) - the name of the package -- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract -- `authors` (optional) - authors of the project -- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) -- `description` (optional) -- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) -- `backend` (optional) -- `license` (optional) -- `expression_width` (optional) - Sets the default backend expression width. This field will override the default backend expression width specified by the Noir compiler (currently set to width 4). - -#### Dependencies section - -This is where you will specify any dependencies for your project. See the [Dependencies page](../../noir/modules_packages_crates/dependencies.md) for more info. - -`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or -verifier contract respectively. - -### main.nr - -The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. - -In our sample program, _main.nr_ looks like this: - -```rust -fn main(x : Field, y : Field) { - assert(x != y); -} -``` - -The parameters `x` and `y` can be seen as the API for the program and must be supplied by the prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when verifying the proof. - -The prover supplies the values for `x` and `y` in the _Prover.toml_ file. - -As for the program body, `assert` ensures that the condition to be satisfied (e.g. `x != y`) is constrained by the proof of the execution of said program (i.e. if the condition was not met, the verifier would reject the proof as an invalid proof). - -### Prover.toml - -The _Prover.toml_ file is a file which the prover uses to supply the inputs to the Noir program (both private and public). - -In our hello world program the _Prover.toml_ file looks like this: - -```toml -x = "1" -y = "2" -``` - -When the command `nargo execute` is executed, nargo will execute the Noir program using the inputs specified in `Prover.toml`, aborting if it finds that these do not satisfy the constraints defined by `main`. In this example, `x` and `y` must satisfy the inequality constraint `assert(x != y)`. - -If an output name is specified such as `nargo execute foo`, the witness generated by this execution will be written to `./target/foo.gz`. This can then be used to generate a proof of the execution. - -#### Arrays of Structs - -The following code shows how to pass an array of structs to a Noir program to generate a proof. - -```rust -// main.nr -struct Foo { - bar: Field, - baz: Field, -} - -fn main(foos: [Foo; 3]) -> pub Field { - foos[2].bar + foos[2].baz -} -``` - -Prover.toml: - -```toml -[[foos]] # foos[0] -bar = 0 -baz = 0 - -[[foos]] # foos[1] -bar = 0 -baz = 0 - -[[foos]] # foos[2] -bar = 1 -baz = 2 -``` - -#### Custom toml files - -You can specify a `toml` file with a different name to use for execution by using the `--prover-name` or `-p` flags. - -This command looks for proof inputs in the default **Prover.toml** and generates the witness and saves it at `./target/foo.gz`: - -```bash -nargo execute foo -``` - -This command looks for proof inputs in the custom **OtherProver.toml** and generates the witness and saves it at `./target/bar.gz`: - -```bash -nargo execute -p OtherProver bar -``` - -Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/_category_.json deleted file mode 100644 index 0c02fb5d4d7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "position": 0, - "label": "Install Nargo", - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/index.md deleted file mode 100644 index 53ea9c7891c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/index.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Nargo Installation -description: - nargo is a command line tool for interacting with Noir programs. This page is a quick guide on how to install Nargo through the most common and easy method, noirup -keywords: [ - Nargo - Noir - Rust - Cargo - Noirup - Installation - Terminal Commands - Version Check - Nightlies - Specific Versions - Branches - Noirup Repository -] -pagination_next: getting_started/hello_noir/index ---- - -`nargo` is a tool for working with Noir programs on the CLI, providing you with the ability to start new projects, compile, execute and test Noir programs from the terminal. - -The name is inspired by Rust's package manager `cargo`; and similar to Rust's `rustup`, Noir also has an easy installation script `noirup`. - -## Installing Noirup - -Open a terminal on your machine, and write: - -```bash -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Close the terminal, open another one, and run - -```bash -noirup -``` - -Done. That's it. You should have the latest version working. You can check with `nargo --version`. - -You can also install nightlies, specific versions -or branches. Check out the [noirup repository](https://github.com/noir-lang/noirup) for more -information. - -Now we're ready to start working on [our first Noir program!](../hello_noir/index.md) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/other_install_methods.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/other_install_methods.md deleted file mode 100644 index 3634723562b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/installation/other_install_methods.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Alternative Installations -description: There are different ways to install Nargo, the one-stop shop and command-line tool for developing Noir programs. This guide explains how to specify which version to install when using noirup, and using WSL for windows. -keywords: [ - Installation - Nargo - Noirup - Binaries - Compiling from Source - WSL for Windows - macOS - Linux - Nix - Direnv - Uninstalling Nargo - ] -sidebar_position: 1 ---- - -## Encouraged Installation Method: Noirup - -Noirup is the endorsed method for installing Nargo, streamlining the process of fetching binaries or compiling from source. It supports a range of options to cater to your specific needs, from nightly builds and specific versions to compiling from various sources. - -### Installing Noirup - -First, ensure you have `noirup` installed: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -### Fetching Binaries - -With `noirup`, you can easily switch between different Nargo versions, including nightly builds: - -- **Nightly Version**: Install the latest nightly build. - - ```sh - noirup --version nightly - ``` - -- **Specific Version**: Install a specific version of Nargo. - ```sh - noirup --version - ``` - -### Compiling from Source - -`noirup` also enables compiling Nargo from various sources: - -- **From a Specific Branch**: Install from the latest commit on a branch. - - ```sh - noirup --branch - ``` - -- **From a Fork**: Install from the main branch of a fork. - - ```sh - noirup --repo - ``` - -- **From a Specific Branch in a Fork**: Install from a specific branch in a fork. - - ```sh - noirup --repo --branch - ``` - -- **From a Specific Pull Request**: Install from a specific PR. - - ```sh - noirup --pr - ``` - -- **From a Specific Commit**: Install from a specific commit. - - ```sh - noirup -C - ``` - -- **From Local Source**: Compile and install from a local directory. - ```sh - noirup --path ./path/to/local/source - ``` - -## Installation on Windows - -The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed natively. However, it is available by using Windows Subsystem for Linux (WSL). - -Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. - -step 2: Follow the [Noirup instructions](#encouraged-installation-method-noirup). - -## Uninstalling Nargo - -If you installed Nargo with `noirup`, you can uninstall Nargo by removing the files in `~/.nargo`, `~/nargo`, and `~/noir_cache`. This ensures that all installed binaries, configurations, and cache related to Nargo are fully removed from your system. - -```bash -rm -r ~/.nargo -rm -r ~/nargo -rm -r ~/noir_cache -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/tooling/noir_codegen.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/tooling/noir_codegen.md deleted file mode 100644 index f7505bef7ab..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/getting_started/tooling/noir_codegen.md +++ /dev/null @@ -1,114 +0,0 @@ ---- -title: Noir Codegen for TypeScript -description: Learn how to use Noir codegen to generate TypeScript bindings -keywords: [Nargo, Noir, compile, TypeScript] -sidebar_position: 3 ---- - -When using TypeScript, it is extra work to interpret Noir program outputs in a type-safe way. Third party libraries may exist for popular Noir programs, but they are either hard to find or unmaintained. - -Now you can generate TypeScript bindings for your Noir programs in two steps: -1. Exporting Noir functions using `nargo export` -2. Using the TypeScript module `noir_codegen` to generate TypeScript binding - -**Note:** you can only export functions from a Noir *library* (not binary or contract program types). - -## Installation - -### Your TypeScript project - -If you don't already have a TypeScript project you can add the module with `yarn` (or `npm`), then initialize it: - -```bash -yarn add typescript -D -npx tsc --init -``` - -### Add TypeScript module - `noir_codegen` - -The following command will add the module to your project's devDependencies: - -```bash -yarn add @noir-lang/noir_codegen -D -``` - -### Nargo library -Make sure you have Nargo, v0.25.0 or greater, installed. If you don't, follow the [installation guide](../installation/index.md). - -If you're in a new project, make a `circuits` folder and create a new Noir library: - -```bash -mkdir circuits && cd circuits -nargo new --lib myNoirLib -``` - -## Usage - -### Export ABI of specified functions - -First go to the `.nr` files in your Noir library, and add the `#[export]` macro to each function that you want to use in TypeScript. - -```rust -#[export] -fn your_function(... -``` - -From your Noir library (where `Nargo.toml` is), run the following command: - -```bash -nargo export -``` - -You will now have an `export` directory with a .json file per exported function. - -You can also specify the directory of Noir programs using `--program-dir`, for example: - -```bash -nargo export --program-dir=./circuits/myNoirLib -``` - -### Generate TypeScript bindings from exported functions - -To use the `noir-codegen` package we added to the TypeScript project: - -```bash -yarn noir-codegen ./export/your_function.json -``` - -This creates an `exports` directory with an `index.ts` file containing all exported functions. - -**Note:** adding `--out-dir` allows you to specify an output dir for your TypeScript bindings to go. Eg: - -```bash -yarn noir-codegen ./export/*.json --out-dir ./path/to/output/dir -``` - -## Example .nr function to .ts output - -Consider a Noir library with this function: - -```rust -#[export] -fn not_equal(x: Field, y: Field) -> bool { - x != y -} -``` - -After the export and codegen steps, you should have an `index.ts` like: - -```typescript -export type Field = string; - - -export const is_equal_circuit: CompiledCircuit = -{"abi":{"parameters":[{"name":"x","type":{"kind":"field"},"visibility":"private"},{"name":"y","type":{"kind":"field"},"visibility":"private"}],"return_type":{"abi_type":{"kind":"boolean"},"visibility":"private"}},"bytecode":"H4sIAAAAAAAA/7WUMQ7DIAxFQ0Krrr2JjSGYLVcpKrn/CaqqDQN12WK+hPBgmWd/wEyHbF1SS923uhOs3pfoChI+wKXMAXzIKyNj4PB0TFTYc0w5RUjoqeAeEu1wqK0F54RGkWvW44LPzExnlkbMEs4JNZmN8PxS42uHv82T8a3Jeyn2Ks+VLPcO558HmyLMCDOXAXXtpPt4R/Rt9T36ss6dS9HGPx/eG17nGegKBQAA"}; - -export async function is_equal(x: Field, y: Field, foreignCallHandler?: ForeignCallHandler): Promise { - const program = new Noir(is_equal_circuit); - const args: InputMap = { x, y }; - const { returnValue } = await program.execute(args, foreignCallHandler); - return returnValue as boolean; -} -``` - -Now the `is_equal()` function and relevant types are readily available for use in TypeScript. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/_category_.json deleted file mode 100644 index 23b560f610b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/_category_.json deleted file mode 100644 index cc2cbb1c253..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugging", - "position": 5, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_the_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_the_repl.md deleted file mode 100644 index 09e5bae68ad..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_the_repl.md +++ /dev/null @@ -1,164 +0,0 @@ ---- -title: Using the REPL Debugger -description: - Step by step guide on how to debug your Noir circuits with the REPL Debugger. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -#### Pre-requisites - -In order to use the REPL debugger, first you need to install recent enough versions of Nargo and vscode-noir. - -## Debugging a simple circuit - -Let's debug a simple circuit: - -```rust -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` - -To start the REPL debugger, using a terminal, go to a Noir circuit's home directory. Then: - -`$ nargo debug` - -You should be seeing this in your terminal: - -``` -[main] Starting debugger -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:9 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> -``` - -The debugger displays the current Noir code location, and it is now waiting for us to drive it. - -Let's first take a look at the available commands. For that we'll use the `help` command. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -Some commands operate only for unconstrained functions, such as `memory` and `memset`. If you try to use them while execution is paused at an ACIR opcode, the debugger will simply inform you that you are not executing unconstrained code: - -``` -> memory -Unconstrained VM memory not available -> -``` - -Before continuing, we can take a look at the initial witness map: - -``` -> witness -_0 = 1 -_1 = 2 -> -``` - -Cool, since `x==1`, `y==2`, and we want to check that `x != y`, our circuit should succeed. At this point we could intervene and use the witness setter command to change one of the witnesses. Let's set `y=3`, then back to 2, so we don't affect the expected result: - -``` -> witness -_0 = 1 -_1 = 2 -> witness 1 3 -_1 = 3 -> witness -_0 = 1 -_1 = 3 -> witness 1 2 -_1 = 2 -> witness -_0 = 1 -_1 = 2 -> -``` - -Now we can inspect the current state of local variables. For that we use the `vars` command. - -``` -> vars -> -``` - -We currently have no vars in context, since we are at the entry point of the program. Let's use `next` to execute until the next point in the program. - -``` -> vars -> next -At ~/noir-examples/recursion/circuits/main/src/main.nr:1:20 - 1 -> fn main(x : Field, y : pub Field) { - 2 assert(x != y); - 3 } -> vars -x:Field = 0x01 -``` - -As a result of stepping, the variable `x`, whose initial value comes from the witness map, is now in context and returned by `vars`. - -``` -> next - 1 fn main(x : Field, y : pub Field) { - 2 -> assert(x != y); - 3 } -> vars -y:Field = 0x02 -x:Field = 0x01 -``` - -Stepping again we can finally see both variables and their values. And now we can see that the next assertion should succeed. - -Let's continue to the end: - -``` -> continue -(Continuing execution...) -Finished execution -> q -[main] Circuit witness successfully solved -``` - -Upon quitting the debugger after a solved circuit, the resulting circuit witness gets saved, equivalent to what would happen if we had run the same circuit with `nargo execute`. - -We just went through the basics of debugging using Noir REPL debugger. For a comprehensive reference, check out [the reference page](../../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_vs_code.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_vs_code.md deleted file mode 100644 index a5858c1a5eb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/debugger/debugging_with_vs_code.md +++ /dev/null @@ -1,68 +0,0 @@ ---- -title: Using the VS Code Debugger -description: - Step by step guide on how to debug your Noir circuits with the VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -This guide will show you how to use VS Code with the vscode-noir extension to debug a Noir project. - -#### Pre-requisites - -- Nargo -- vscode-noir -- A Noir project with a `Nargo.toml`, `Prover.toml` and at least one Noir (`.nr`) containing an entry point function (typically `main`). - -## Running the debugger - -The easiest way to start debugging is to open the file you want to debug, and press `F5`. This will cause the debugger to launch, using your `Prover.toml` file as input. - -You should see something like this: - -![Debugger launched](@site/static/img/debugger/1-started.png) - -Let's inspect the state of the program. For that, we open VS Code's _Debug pane_. Look for this icon: - -![Debug pane icon](@site/static/img/debugger/2-icon.png) - -You will now see two categories of variables: Locals and Witness Map. - -![Debug pane expanded](@site/static/img/debugger/3-debug-pane.png) - -1. **Locals**: variables of your program. At this point in execution this section is empty, but as we step through the code it will get populated by `x`, `result`, `digest`, etc. - -2. **Witness map**: these are initially populated from your project's `Prover.toml` file. In this example, they will be used to populate `x` and `result` at the beginning of the `main` function. - -Most of the time you will probably be focusing mostly on locals, as they represent the high level state of your program. - -You might be interested in inspecting the witness map in case you are trying to solve a really low level issue in the compiler or runtime itself, so this concerns mostly advanced or niche users. - -Let's step through the program, by using the debugger buttons or their corresponding keyboard shortcuts. - -![Debugger buttons](@site/static/img/debugger/4-debugger-buttons.png) - -Now we can see in the variables pane that there's values for `digest`, `result` and `x`. - -![Inspecting locals](@site/static/img/debugger/5-assert.png) - -We can also inspect the values of variables by directly hovering on them on the code. - -![Hover locals](@site/static/img/debugger/6-hover.png) - -Let's set a break point at the `keccak256` function, so we can continue execution up to the point when it's first invoked without having to go one step at a time. - -We just need to click the to the right of the line number 18. Once the breakpoint appears, we can click the `continue` button or use its corresponding keyboard shortcut (`F5` by default). - -![Breakpoint](@site/static/img/debugger/7-break.png) - -Now we are debugging the `keccak256` function, notice the _Call Stack pane_ at the lower right. This lets us inspect the current call stack of our process. - -That covers most of the current debugger functionalities. Check out [the reference](../../reference/debugger/debugger_vscode.md) for more details on how to configure the debugger. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-oracles.md deleted file mode 100644 index 2d2ed5c94b9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-oracles.md +++ /dev/null @@ -1,273 +0,0 @@ ---- -title: How to use Oracles -description: Learn how to use oracles in your Noir program with examples in both Nargo and NoirJS. This guide also covers writing a JSON RPC server and providing custom foreign call handlers for NoirJS. -keywords: - - Noir Programming - - Oracles - - Nargo - - NoirJS - - JSON RPC Server - - Foreign Call Handlers -sidebar_position: 1 ---- - -This guide shows you how to use oracles in your Noir program. For the sake of clarity, it assumes that: - -- You have read the [explainer on Oracles](../explainers/explainer-oracle.md) and are comfortable with the concept. -- You have a Noir program to add oracles to. You can create one using the [vite-hardhat starter](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) as a boilerplate. -- You understand the concept of a JSON-RPC server. Visit the [JSON-RPC website](https://www.jsonrpc.org/) if you need a refresher. -- You are comfortable with server-side JavaScript (e.g. Node.js, managing packages, etc.). - -For reference, you can find the snippets used in this tutorial on the [Aztec DevRel Repository](https://github.com/AztecProtocol/dev-rel/tree/main/code-snippets/how-to-oracles). - -## Rundown - -This guide has 3 major steps: - -1. How to modify our Noir program to make use of oracle calls as unconstrained functions -2. How to write a JSON RPC Server to resolve these oracle calls with Nargo -3. How to use them in Nargo and how to provide a custom resolver in NoirJS - -## Step 1 - Modify your Noir program - -An oracle is defined in a Noir program by defining two methods: - -- An unconstrained method - This tells the compiler that it is executing an [unconstrained functions](../noir/concepts//unconstrained.md). -- A decorated oracle method - This tells the compiler that this method is an RPC call. - -An example of an oracle that returns a `Field` would be: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(number: Field) -> Field { } - -unconstrained fn get_sqrt(number: Field) -> Field { - sqrt(number) -} -``` - -In this example, we're wrapping our oracle function in a unconstrained method, and decorating it with `oracle(getSqrt)`. We can then call the unconstrained function as we would call any other function: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); -} -``` - -In the next section, we will make this `getSqrt` (defined on the `sqrt` decorator) be a method of the RPC server Noir will use. - -:::danger - -As explained in the [Oracle Explainer](../explainers/explainer-oracle.md), this `main` function is unsafe unless you constrain its return value. For example: - -```rust -fn main(input: Field) { - let sqrt = get_sqrt(input); - assert(sqrt.pow_32(2) as u64 == input as u64); // <---- constrain the return of an oracle! -} -``` - -::: - -:::info - -Currently, oracles only work with single params or array params. For example: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt([Field; 2]) -> [Field; 2] { } -``` - -::: - -## Step 2 - Write an RPC server - -Brillig will call *one* RPC server. Most likely you will have to write your own, and you can do it in whatever language you prefer. In this guide, we will do it in Javascript. - -Let's use the above example of an oracle that consumes an array with two `Field` and returns their square roots: - -```rust -#[oracle(getSqrt)] -unconstrained fn sqrt(input: [Field; 2]) -> [Field; 2] { } - -unconstrained fn get_sqrt(input: [Field; 2]) -> [Field; 2] { - sqrt(input) -} - -fn main(input: [Field; 2]) { - let sqrt = get_sqrt(input); - assert(sqrt[0].pow_32(2) as u64 == input[0] as u64); - assert(sqrt[1].pow_32(2) as u64 == input[1] as u64); -} -``` - -:::info - -Why square root? - -In general, computing square roots is computationally more expensive than multiplications, which takes a toll when speaking about ZK applications. In this case, instead of calculating the square root in Noir, we are using our oracle to offload that computation to be made in plain. In our circuit we can simply multiply the two values. - -::: - -Now, we should write the correspondent RPC server, starting with the [default JSON-RPC 2.0 boilerplate](https://www.npmjs.com/package/json-rpc-2.0#example): - -```js -import { JSONRPCServer } from "json-rpc-2.0"; -import express from "express"; -import bodyParser from "body-parser"; - -const app = express(); -app.use(bodyParser.json()); - -const server = new JSONRPCServer(); -app.post("/", (req, res) => { - const jsonRPCRequest = req.body; - server.receive(jsonRPCRequest).then((jsonRPCResponse) => { - if (jsonRPCResponse) { - res.json(jsonRPCResponse); - } else { - res.sendStatus(204); - } - }); -}); - -app.listen(5555); -``` - -Now, we will add our `getSqrt` method, as expected by the `#[oracle(getSqrt)]` decorator in our Noir code. It maps through the params array and returns their square roots: - -```js -server.addMethod("resolve_function_call", async (params) => { - if params.function !== "getSqrt" { - throw Error("Unexpected foreign call") - }; - const values = params.inputs[0].Array.map((field) => { - return `${Math.sqrt(parseInt(field, 16))}`; - }); - return { values: [{ Array: values }] }; -}); -``` - -If you're using Typescript, the following types may be helpful in understanding the expected return value and making sure they're easy to follow: - -```js -interface SingleForeignCallParam { - Single: string, -} - -interface ArrayForeignCallParam { - Array: string[], -} - -type ForeignCallParam = SingleForeignCallParam | ArrayForeignCallParam; - -interface ForeignCallResult { - values: ForeignCallParam[], -} -``` - -::: Multidimensional Arrays - -If the Oracle function is returning an array containing other arrays, such as `[['1','2],['3','4']]`, you need to provide the values in json as flattened values. In the previous example, it would be `['1', '2', '3', '4']`. In the noir program, the Oracle signature can use a nested type, the flattened values will be automatically converted to the nested type. - -::: - -## Step 3 - Usage with Nargo - -Using the [`nargo` CLI tool](../getting_started/installation/index.md), you can use oracles in the `nargo test` and `nargo execute` commands by passing a value to `--oracle-resolver`. For example: - -```bash -nargo test --oracle-resolver http://localhost:5555 -``` - -This tells `nargo` to use your RPC Server URL whenever it finds an oracle decorator. - -## Step 4 - Usage with NoirJS - -In a JS environment, an RPC server is not strictly necessary, as you may want to resolve your oracles without needing any JSON call at all. NoirJS simply expects that you pass a callback function when you generate proofs, and that callback function can be anything. - -For example, if your Noir program expects the host machine to provide CPU pseudo-randomness, you could simply pass it as the `foreignCallHandler`. You don't strictly need to create an RPC server to serve pseudo-randomness, as you may as well get it directly in your app: - -```js -const foreignCallHandler = (name, inputs) => crypto.randomBytes(16) // etc - -await noir.execute(inputs, foreignCallHandler) -``` - -As one can see, in NoirJS, the [`foreignCallHandler`](../reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md) function simply means "a callback function that returns a value of type [`ForeignCallOutput`](../reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md). It doesn't have to be an RPC call like in the case for Nargo. - -:::tip - -Does this mean you don't have to write an RPC server like in [Step #2](#step-2---write-an-rpc-server)? - -You don't technically have to, but then how would you run `nargo test`? To use both `Nargo` and `NoirJS` in your development flow, you will have to write a JSON RPC server. - -::: - -In this case, let's make `foreignCallHandler` call the JSON RPC Server we created in [Step #2](#step-2---write-an-rpc-server), by making it a JSON RPC Client. - -For example, using the same `getSqrt` program in [Step #1](#step-1---modify-your-noir-program) (comments in the code): - -```js -import { JSONRPCClient } from "json-rpc-2.0"; - -// declaring the JSONRPCClient -const client = new JSONRPCClient((jsonRPCRequest) => { -// hitting the same JSON RPC Server we coded above - return fetch("http://localhost:5555", { - method: "POST", - headers: { - "content-type": "application/json", - }, - body: JSON.stringify(jsonRPCRequest), - }).then((response) => { - if (response.status === 200) { - return response - .json() - .then((jsonRPCResponse) => client.receive(jsonRPCResponse)); - } else if (jsonRPCRequest.id !== undefined) { - return Promise.reject(new Error(response.statusText)); - } - }); -}); - -// declaring a function that takes the name of the foreign call (getSqrt) and the inputs -const foreignCallHandler = async (name, input) => { - // notice that the "inputs" parameter contains *all* the inputs - // in this case we to make the RPC request with the first parameter "numbers", which would be input[0] - const oracleReturn = await client.request(name, [ - { Array: input[0].map((i) => i.toString("hex")) }, - ]); - return [oracleReturn.values[0].Array]; -}; - -// the rest of your NoirJS code -const input = { input: [4, 16] }; -const { witness } = await noir.execute(numbers, foreignCallHandler); -``` - -:::tip - -If you're in a NoirJS environment running your RPC server together with a frontend app, you'll probably hit a familiar problem in full-stack development: requests being blocked by [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) policy. For development only, you can simply install and use the [`cors` npm package](https://www.npmjs.com/package/cors) to get around the problem: - -```bash -yarn add cors -``` - -and use it as a middleware: - -```js -import cors from "cors"; - -const app = express(); -app.use(cors()) -``` - -::: - -## Conclusion - -Hopefully by the end of this guide, you should be able to: - -- Write your own logic around Oracles and how to write a JSON RPC server to make them work with your Nargo commands. -- Provide custom foreign call handlers for NoirJS. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-recursion.md deleted file mode 100644 index aac84e29fac..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-recursion.md +++ /dev/null @@ -1,180 +0,0 @@ ---- -title: How to use recursion on NoirJS -description: Learn how to implement recursion with NoirJS, a powerful tool for creating smart contracts on the EVM blockchain. This guide assumes familiarity with NoirJS, solidity verifiers, and the Barretenberg proving backend. Discover how to generate both final and intermediate proofs using `noir_js` and `backend_barretenberg`. -keywords: - [ - "NoirJS", - "EVM blockchain", - "smart contracts", - "recursion", - "solidity verifiers", - "Barretenberg backend", - "noir_js", - "backend_barretenberg", - "intermediate proofs", - "final proofs", - "nargo compile", - "json import", - "recursive circuit", - "recursive app" - ] -sidebar_position: 1 ---- - -This guide shows you how to use recursive proofs in your NoirJS app. For the sake of clarity, it is assumed that: - -- You already have a NoirJS app. If you don't, please visit the [NoirJS tutorial](../tutorials/noirjs_app.md) and the [reference](../reference/NoirJS/noir_js/index.md). -- You are familiar with what are recursive proofs and you have read the [recursion explainer](../explainers/explainer-recursion.md) -- You already built a recursive circuit following [the reference](../noir/standard_library/recursion.md), and understand how it works. - -It is also assumed that you're not using `noir_wasm` for compilation, and instead you've used [`nargo compile`](../reference/nargo_commands.md) to generate the `json` you're now importing into your project. However, the guide should work just the same if you're using `noir_wasm`. - -:::info - -As you've read in the [explainer](../explainers/explainer-recursion.md), a recursive proof is an intermediate proof. This means that it doesn't necessarily generate the final step that makes it verifiable in a smart contract. However, it is easy to verify within another circuit. - -While "standard" usage of NoirJS packages abstracts final proofs, it currently lacks the necessary interface to abstract away intermediate proofs. This means that these proofs need to be created by using the backend directly. - -In short: - -- `noir_js` generates *only* final proofs -- `backend_barretenberg` generates both types of proofs - -::: - -In a standard recursive app, you're also dealing with at least two circuits. For the purpose of this guide, we will assume the following: - -- `main`: a circuit of type `assert(x != y)`, where `main` is marked with a `#[recursive]` attribute. This attribute states that the backend should generate proofs that are friendly for verification within another circuit. -- `recursive`: a circuit that verifies `main` - -For a full example on how recursive proofs work, please refer to the [noir-examples](https://github.com/noir-lang/noir-examples) repository. We will *not* be using it as a reference for this guide. - -## Step 1: Setup - -In a common NoirJS app, you need to instantiate a backend with something like `const backend = new Backend(circuit)`. Then you feed it to the `noir_js` interface. - -For recursion, this doesn't happen, and the only need for `noir_js` is only to `execute` a circuit and get its witness and return value. Everything else is not interfaced, so it needs to happen on the `backend` object. - -It is also recommended that you instantiate the backend with as many threads as possible, to allow for maximum concurrency: - -```js -const backend = new Backend(circuit, { threads: 8 }) -``` - -:::tip -You can use the [`os.cpus()`](https://nodejs.org/api/os.html#oscpus) object in `nodejs` or [`navigator.hardwareConcurrency`](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/hardwareConcurrency) on the browser to make the most out of those glorious cpu cores -::: - -## Step 2: Generating the witness and the proof for `main` - -After instantiating the backend, you should also instantiate `noir_js`. We will use it to execute the circuit and get the witness. - -```js -const noir = new Noir(circuit) -const { witness } = noir.execute(input) -``` - -With this witness, you are now able to generate the intermediate proof for the main circuit: - -```js -const { proof, publicInputs } = await backend.generateProof(witness) -``` - -:::warning - -Always keep in mind what is actually happening on your development process, otherwise you'll quickly become confused about what circuit we are actually running and why! - -In this case, you can imagine that Alice (running the `main` circuit) is proving something to Bob (running the `recursive` circuit), and Bob is verifying her proof within his proof. - -With this in mind, it becomes clear that our intermediate proof is the one *meant to be verified within another circuit*, so it must be Alice's. Actually, the only final proof in this theoretical scenario would be the last one, sent on-chain. - -::: - -## Step 3 - Verification and proof artifacts - -Optionally, you are able to verify the intermediate proof: - -```js -const verified = await backend.verifyProof({ proof, publicInputs }) -``` - -This can be useful to make sure our intermediate proof was correctly generated. But the real goal is to do it within another circuit. For that, we need to generate recursive proof artifacts that will be passed to the circuit that is verifying the proof we just generated. Instead of passing the proof and verification key as a byte array, we pass them as fields which makes it cheaper to verify in a circuit: - -```js -const { proofAsFields, vkAsFields, vkHash } = await backend.generateRecursiveProofArtifacts( { publicInputs, proof }, publicInputsCount) -``` - -This call takes the public inputs and the proof, but also the public inputs count. While this is easily retrievable by simply counting the `publicInputs` length, the backend interface doesn't currently abstract it away. - -:::info - -The `proofAsFields` has a constant size `[Field; 93]` and verification keys in Barretenberg are always `[Field; 114]`. - -::: - -:::warning - -One common mistake is to forget *who* makes this call. - -In a situation where Alice is generating the `main` proof, if she generates the proof artifacts and sends them to Bob, which gladly takes them as true, this would mean Alice could prove anything! - -Instead, Bob needs to make sure *he* extracts the proof artifacts, using his own instance of the `main` circuit backend. This way, Alice has to provide a valid proof for the correct `main` circuit. - -::: - -## Step 4 - Recursive proof generation - -With the artifacts, generating a recursive proof is no different from a normal proof. You simply use the `backend` (with the recursive circuit) to generate it: - -```js -const recursiveInputs = { - verification_key: vkAsFields, // array of length 114 - proof: proofAsFields, // array of length 93 + size of public inputs - publicInputs: [mainInput.y], // using the example above, where `y` is the only public input - key_hash: vkHash, -} - -const { witness, returnValue } = noir.execute(recursiveInputs) // we're executing the recursive circuit now! -const { proof, publicInputs } = backend.generateProof(witness) -const verified = backend.verifyProof({ proof, publicInputs }) -``` - -You can obviously chain this proof into another proof. In fact, if you're using recursive proofs, you're probably interested of using them this way! - -:::tip - -Managing circuits and "who does what" can be confusing. To make sure your naming is consistent, you can keep them in an object. For example: - -```js -const circuits = { - main: mainJSON, - recursive: recursiveJSON -} -const backends = { - main: new BarretenbergBackend(circuits.main), - recursive: new BarretenbergBackend(circuits.recursive) -} -const noir_programs = { - main: new Noir(circuits.main), - recursive: new Noir(circuits.recursive) -} -``` - -This allows you to neatly call exactly the method you want without conflicting names: - -```js -// Alice runs this 👇 -const { witness: mainWitness } = await noir_programs.main.execute(input) -const proof = await backends.main.generateProof(mainWitness) - -// Bob runs this 👇 -const verified = await backends.main.verifyProof(proof) -const { proofAsFields, vkAsFields, vkHash } = await backends.main.generateRecursiveProofArtifacts( - proof, - numPublicInputs, -); -const { witness: recursiveWitness } = await noir_programs.recursive.execute(recursiveInputs) -const recursiveProof = await backends.recursive.generateProof(recursiveWitness); -``` - -::: diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-solidity-verifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-solidity-verifier.md deleted file mode 100644 index e6ed9abaec6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/how-to-solidity-verifier.md +++ /dev/null @@ -1,251 +0,0 @@ ---- -title: Generate a Solidity Verifier -description: - Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier - contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart - contract. Read more to find out -keywords: - [ - solidity verifier, - smart contract, - blockchain, - compiler, - plonk_vk.sol, - EVM blockchain, - verifying Noir programs, - proving backend, - Barretenberg, - ] -sidebar_position: 0 -pagination_next: tutorials/noirjs_app ---- - -Noir has the ability to generate a verifier contract in Solidity, which can be deployed in many EVM-compatible blockchains such as Ethereum. - -This allows for a powerful feature set, as one can make use of the conciseness and the privacy provided by Noir in an immutable ledger. Applications can range from simple P2P guessing games, to complex private DeFi interactions. - -This guide shows you how to generate a Solidity Verifier and deploy it on the [Remix IDE](https://remix.ethereum.org/). It is assumed that: - -- You are comfortable with the Solidity programming language and understand how contracts are deployed on the Ethereum network -- You have Noir installed and you have a Noir program. If you don't, [get started](../getting_started/installation/index.md) with Nargo and the example Hello Noir circuit -- You are comfortable navigating RemixIDE. If you aren't or you need a refresher, you can find some video tutorials [here](https://www.youtube.com/channel/UCjTUPyFEr2xDGN6Cg8nKDaA) that could help you. - -## Rundown - -Generating a Solidity Verifier contract is actually a one-command process. However, compiling it and deploying it can have some caveats. Here's the rundown of this guide: - -1. How to generate a solidity smart contract -2. How to compile the smart contract in the RemixIDE -3. How to deploy it to a testnet - -## Step 1 - Generate a contract - -This is by far the most straight-forward step. Just run: - -```sh -nargo compile -``` - -This will compile your source code into a Noir build artifact to be stored in the `./target` directory, you can then generate the smart contract using the commands: - -```sh -# Here we pass the path to the newly generated Noir artifact. -bb write_vk -b ./target/.json -bb contract -``` - -replacing `` with the name of your Noir project. A new `contract` folder would then be generated in your project directory, containing the Solidity -file `contract.sol`. It can be deployed to any EVM blockchain acting as a verifier smart contract. - -:::info - -It is possible to generate verifier contracts of Noir programs for other smart contract platforms as long as the proving backend supplies an implementation. - -Barretenberg, the default proving backend for Nargo, supports generation of verifier contracts, for the time being these are only in Solidity. -::: - -## Step 2 - Compiling - -We will mostly skip the details of RemixIDE, as the UI can change from version to version. For now, we can just open -Remix and create a blank workspace. - -![Create Workspace](@site/static/img/how-tos/solidity_verifier_1.png) - -We will create a new file to contain the contract Nargo generated, and copy-paste its content. - -:::warning - -You'll likely see a warning advising you to not trust pasted code. While it is an important warning, it is irrelevant in the context of this guide and can be ignored. We will not be deploying anywhere near a mainnet. - -::: - -To compile our the verifier, we can navigate to the compilation tab: - -![Compilation Tab](@site/static/img/how-tos/solidity_verifier_2.png) - -Remix should automatically match a suitable compiler version. However, hitting the "Compile" button will most likely generate a "Stack too deep" error: - -![Stack too deep](@site/static/img/how-tos/solidity_verifier_3.png) - -This is due to the verify function needing to put many variables on the stack, but enabling the optimizer resolves the issue. To do this, let's open the "Advanced Configurations" tab and enable optimization. The default 200 runs will suffice. - -:::info - -This time we will see a warning about an unused function parameter. This is expected, as the `verify` function doesn't use the `_proof` parameter inside a solidity block, it is loaded from calldata and used in assembly. - -::: - -![Compilation success](@site/static/img/how-tos/solidity_verifier_4.png) - -## Step 3 - Deploying - -At this point we should have a compiled contract read to deploy. If we navigate to the deploy section in Remix, we will see many different environments we can deploy to. The steps to deploy on each environment would be out-of-scope for this guide, so we will just use the default Remix VM. - -Looking closely, we will notice that our "Solidity Verifier" is actually three contracts working together: - -- An `UltraVerificationKey` library which simply stores the verification key for our circuit. -- An abstract contract `BaseUltraVerifier` containing most of the verifying logic. -- A main `UltraVerifier` contract that inherits from the Base and uses the Key contract. - -Remix will take care of the dependencies for us so we can simply deploy the UltraVerifier contract by selecting it and hitting "deploy": - -![Deploying UltraVerifier](@site/static/img/how-tos/solidity_verifier_5.png) - -A contract will show up in the "Deployed Contracts" section, where we can retrieve the Verification Key Hash. This is particularly useful for double-checking the deployer contract is the correct one. - -:::note - -Why "UltraVerifier"? - -To be precise, the Noir compiler (`nargo`) doesn't generate the verifier contract directly. It compiles the Noir code into an intermediate language (ACIR), which is then executed by the backend. So it is the backend that returns the verifier smart contract, not Noir. - -In this case, the Barretenberg Backend uses the UltraPlonk proving system, hence the "UltraVerifier" name. - -::: - -## Step 4 - Verifying - -To verify a proof using the Solidity verifier contract, we call the `verify` function in this extended contract: - -```solidity -function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) -``` - -When using the default example in the [Hello Noir](../getting_started/hello_noir/index.md) guide, the easiest way to confirm that the verifier contract is doing its job is by calling the `verify` function via remix with the required parameters. Note that the public inputs must be passed in separately to the rest of the proof so we must split the proof as returned from `bb`. - -First generate a proof with `bb` at the location `./proof` using the steps in [get started](../getting_started/hello_noir/index.md), this proof is in a binary format but we want to convert it into a hex string to pass into Remix, this can be done with the - -```bash -# This value must be changed to match the number of public inputs (including return values!) in your program. -NUM_PUBLIC_INPUTS=1 -PUBLIC_INPUT_BYTES=32*NUM_PUBLIC_INPUTS -HEX_PUBLIC_INPUTS=$(head -c $PUBLIC_INPUT_BYTES ./proof | od -An -v -t x1 | tr -d $' \n') -HEX_PROOF=$(tail -c +$(($PUBLIC_INPUT_BYTES + 1)) ./proof | od -An -v -t x1 | tr -d $' \n') - -echo "Public inputs:" -echo $HEX_PUBLIC_INPUTS - -echo "Proof:" -echo "0x$HEX_PROOF" -``` - -Remix expects that the public inputs will be split into an array of `bytes32` values so `HEX_PUBLIC_INPUTS` needs to be split up into 32 byte chunks which are prefixed with `0x` accordingly. - -A programmatic example of how the `verify` function is called can be seen in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): - -```solidity -function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { - // ... - bytes32[] memory publicInputs = new bytes32[](4); - publicInputs[0] = merkleRoot; - publicInputs[1] = bytes32(proposalId); - publicInputs[2] = bytes32(vote); - publicInputs[3] = nullifierHash; - require(verifier.verify(proof, publicInputs), "Invalid proof"); -``` - -:::info[Return Values] - -A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in Noir. - -Under the hood, the return value is passed as an input to the circuit and is checked at the end of the circuit program. - -For example, if you have Noir program like this: - -```rust -fn main( - // Public inputs - pubkey_x: pub Field, - pubkey_y: pub Field, - // Private inputs - priv_key: Field, -) -> pub Field -``` - -the `verify` function will expect the public inputs array (second function parameter) to be of length 3, the two inputs and the return value. - -Passing only two inputs will result in an error such as `PUBLIC_INPUT_COUNT_INVALID(3, 2)`. - -In this case, the inputs parameter to `verify` would be an array ordered as `[pubkey_x, pubkey_y, return`. - -::: - -:::tip[Structs] - -You can pass structs to the verifier contract. They will be flattened so that the array of inputs is 1-dimensional array. - -For example, consider the following program: - -```rust -struct Type1 { - val1: Field, - val2: Field, -} - -struct Nested { - t1: Type1, - is_true: bool, -} - -fn main(x: pub Field, nested: pub Nested, y: pub Field) { - //... -} -``` - -The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` - -::: - -The other function you can call is our entrypoint `verify` function, as defined above. - -:::tip - -It's worth noticing that the `verify` function is actually a `view` function. A `view` function does not alter the blockchain state, so it doesn't need to be distributed (i.e. it will run only on the executing node), and therefore doesn't cost any gas. - -This can be particularly useful in some situations. If Alice generated a proof and wants Bob to verify its correctness, Bob doesn't need to run Nargo, NoirJS, or any Noir specific infrastructure. He can simply make a call to the blockchain with the proof and verify it is correct without paying any gas. - -It would be incorrect to say that a Noir proof verification costs any gas at all. However, most of the time the result of `verify` is used to modify state (for example, to update a balance, a game state, etc). In that case the whole network needs to execute it, which does incur gas costs (calldata and execution, but not storage). - -::: - -## A Note on EVM chains - -Noir proof verification requires the ecMul, ecAdd and ecPairing precompiles. Not all EVM chains support EC Pairings, notably some of the ZK-EVMs. This means that you won't be able to use the verifier contract in all of them. You can find an incomplete list of which EVM chains support these precompiles [here](https://www.evmdiff.com/features?feature=precompiles). - -For example, chains like `zkSync ERA` and `Polygon zkEVM` do not currently support these precompiles, so proof verification via Solidity verifier contracts won't work. Here's a quick list of EVM chains that have been tested and are known to work: - -- Optimism -- Arbitrum -- Polygon PoS -- Scroll -- Celo - -If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. - -## What's next - -Now that you know how to call a Noir Solidity Verifier on a smart contract using Remix, you should be comfortable with using it with some programmatic frameworks, such as [hardhat](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat) and [foundry](https://github.com/noir-lang/noir-starter/tree/main/with-foundry). - -You can find other tools, examples, boilerplates and libraries in the [awesome-noir](https://github.com/noir-lang/awesome-noir) repository. - -You should also be ready to write and deploy your first NoirJS app and start generating proofs on websites, phones, and NodeJS environments! Head on to the [NoirJS tutorial](../tutorials/noirjs_app.md) to learn how to do that. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/merkle-proof.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/merkle-proof.mdx deleted file mode 100644 index 0a128adb2de..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/merkle-proof.mdx +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Prove Merkle Tree Membership -description: - Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a - merkle tree with a specified root, at a given index. -keywords: - [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] -sidebar_position: 4 ---- - -Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is -in a merkle tree. - -```rust - -fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { - let leaf = std::hash::hash_to_field(message.as_slice()); - let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); - assert(merkle_root == root); -} - -``` - -The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen -by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` -instead. - -```rust -let leaf = std::hash::hash_to_field(message.as_slice()); -``` - -The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. - -```rust -let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); -assert (merkle_root == root); -``` - -> **Note:** It is possible to re-implement the merkle tree implementation without standard library. -> However, for most usecases, it is enough. In general, the standard library will always opt to be -> as conservative as possible, while striking a balance with efficiency. - -An example, the merkle membership proof, only requires a hash function that has collision -resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient -than the even more conservative sha256. - -[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/using-devcontainers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/using-devcontainers.mdx deleted file mode 100644 index 727ec6ca667..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/how_to/using-devcontainers.mdx +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Developer Containers and Codespaces -description: "Learn how to set up a devcontainer in your GitHub repository for a seamless coding experience with Codespaces. Follow our easy 8-step guide to create your own Noir environment without installing Nargo locally." -keywords: ["Devcontainer", "Codespaces", "GitHub", "Noir Environment", "Docker Image", "Development Environment", "Remote Coding", "GitHub Codespaces", "Noir Programming", "Nargo", "VSCode Extensions", "Noirup"] -sidebar_position: 1 ---- - -Adding a developer container configuration file to your Noir project is one of the easiest way to unlock coding in browser. - -## What's a devcontainer after all? - -A [Developer Container](https://containers.dev/) (devcontainer for short) is a Docker image that comes preloaded with tools, extensions, and other tools you need to quickly get started or continue a project, without having to install Nargo locally. Think of it as a development environment in a box. - -There are many advantages to this: - -- It's platform and architecture agnostic -- You don't need to have an IDE installed, or Nargo, or use a terminal at all -- It's safer for using on a public machine or public network - -One of the best ways of using devcontainers is... not using your machine at all, for maximum control, performance, and ease of use. -Enter Codespaces. - -## Codespaces - -If a devcontainer is just a Docker image, then what stops you from provisioning a `p3dn.24xlarge` AWS EC2 instance with 92 vCPUs and 768 GiB RAM and using it to prove your 10-gate SNARK proof? - -Nothing! Except perhaps the 30-40$ per hour it will cost you. - -The problem is that provisioning takes time, and I bet you don't want to see the AWS console every time you want to code something real quick. - -Fortunately, there's an easy and free way to get a decent remote machine ready and loaded in less than 2 minutes: Codespaces. [Codespaces is a Github feature](https://github.com/features/codespaces) that allows you to code in a remote machine by using devcontainers, and it's pretty cool: - -- You can start coding Noir in less than a minute -- It uses the resources of a remote machine, so you can code on your grandma's phone if needed be -- It makes it easy to share work with your frens -- It's fully reusable, you can stop and restart whenever you need to - -:::info - -Don't take out your wallet just yet. Free GitHub accounts get about [15-60 hours of coding](https://github.com/features/codespaces) for free per month, depending on the size of your provisioned machine. - -::: - -## Tell me it's _actually_ easy - -It is! - -Github comes with a default codespace and you can use it to code your own devcontainer. That's exactly what we will be doing in this guide. - - - -8 simple steps: - -#### 1. Create a new repository on GitHub. - -#### 2. Click "Start coding with Codespaces". This will use the default image. - -#### 3. Create a folder called `.devcontainer` in the root of your repository. - -#### 4. Create a Dockerfile in that folder, and paste the following code: - -```docker -FROM --platform=linux/amd64 node:lts-bookworm-slim -SHELL ["/bin/bash", "-c"] -RUN apt update && apt install -y curl bash git tar gzip libc++-dev -RUN curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -ENV PATH="/root/.nargo/bin:$PATH" -RUN noirup -ENTRYPOINT ["nargo"] -``` -#### 5. Create a file called `devcontainer.json` in the same folder, and paste the following code: - -```json -{ - "name": "Noir on Codespaces", - "build": { - "context": ".", - "dockerfile": "Dockerfile" - }, - "customizations": { - "vscode": { - "extensions": ["noir-lang.vscode-noir"] - } - } -} -``` -#### 6. Commit and push your changes - -This will pull the new image and build it, so it could take a minute or so - -#### 8. Done! -Just wait for the build to finish, and there's your easy Noir environment. - - -Refer to [noir-starter](https://github.com/noir-lang/noir-starter/) as an example of how devcontainers can be used together with codespaces. - - - -## How do I use it? - -Using the codespace is obviously much easier than setting it up. -Just navigate to your repository and click "Code" -> "Open with Codespaces". It should take a few seconds to load, and you're ready to go. - -:::info - -If you really like the experience, you can add a badge to your readme, links to existing codespaces, and more. -Check out the [official docs](https://docs.github.com/en/codespaces/setting-up-your-project-for-codespaces/setting-up-your-repository/facilitating-quick-creation-and-resumption-of-codespaces) for more info. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/index.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/index.mdx deleted file mode 100644 index a6bd306f91d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/index.mdx +++ /dev/null @@ -1,67 +0,0 @@ ---- -title: Noir Lang -hide_title: true -description: - Learn about the public alpha release of Noir, a domain specific language heavily influenced by Rust that compiles to - an intermediate language which can be compiled to an arithmetic circuit or a rank-1 constraint system. -keywords: - [Noir, - Domain Specific Language, - Rust, - Intermediate Language, - Arithmetic Circuit, - Rank-1 Constraint System, - Ethereum Developers, - Protocol Developers, - Blockchain Developers, - Proving System, - Smart Contract Language] -sidebar_position: 0 ---- - -import Tabs from '@theme/Tabs'; -import TabItem from '@theme/TabItem'; - -Noir Logo - -Noir is an open-source Domain-Specific Language for safe and seamless construction of privacy-preserving Zero-Knowledge programs, requiring no previous knowledge on the underlying mathematics or cryptography. - -ZK programs are programs that can generate short proofs of statements without revealing all inputs to the statements. You can read more about Zero-Knowledge Proofs [here](https://dev.to/spalladino/a-beginners-intro-to-coding-zero-knowledge-proofs-c56). - -## What's new about Noir? - -Noir works differently from most ZK languages by taking a two-pronged path. First, it compiles the program to an adaptable intermediate language known as ACIR. From there, depending on a given project's needs, ACIR can be further compiled into an arithmetic circuit for integration with the proving backend. - -:::info - -Noir is backend agnostic, which means it makes no assumptions on which proving backend powers the ZK proof. Being the language that powers [Aztec Contracts](https://docs.aztec.network/developers/contracts/main), it defaults to Aztec's Barretenberg proving backend. - -However, the ACIR output can be transformed to be compatible with other PLONK-based backends, or into a [rank-1 constraint system](https://www.rareskills.io/post/rank-1-constraint-system) suitable for backends such as Arkwork's Marlin. - -::: - -## Who is Noir for? - -Noir can be used both in complex cloud-based backends and in user's smartphones, requiring no knowledge on the underlying math or cryptography. From authorization systems that keep a password in the user's device, to complex on-chain verification of recursive proofs, Noir is designed to abstract away complexity without any significant overhead. Here are some examples of situations where Noir can be used: - - - - Noir Logo - - Aztec Contracts leverage Noir to allow for the storage and execution of private information. Writing an Aztec Contract is as easy as writing Noir, and Aztec developers can easily interact with the network storage and execution through the [Aztec.nr](https://docs.aztec.network/developers/contracts/main) library. - - - Soliditry Verifier Example - Noir can auto-generate Solidity verifier contracts that verify Noir proofs. This allows for non-interactive verification of proofs containing private information in an immutable system. This feature powers a multitude of use-case scenarios, from P2P chess tournaments, to [Aztec Layer-2 Blockchain](https://docs.aztec.network/) - - - Aztec Labs developed NoirJS, an easy interface to generate and verify Noir proofs in a Javascript environment. This allows for Noir to be used in webpages, mobile apps, games, and any other environment supporting JS execution in a standalone manner. - - - - -## Libraries - -Noir is meant to be easy to extend by simply importing Noir libraries just like in Rust. -The [awesome-noir repo](https://github.com/noir-lang/awesome-noir#libraries) is a collection of libraries developed by the Noir community. -Writing a new library is easy and makes code be composable and easy to reuse. See the section on [dependencies](noir/modules_packages_crates/dependencies.md) for more information. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/migration_notes.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/migration_notes.md deleted file mode 100644 index 6bd740024e5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/migration_notes.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Migration notes -description: Read about migration notes from previous versions, which could solve problems while updating -keywords: [Noir, notes, migration, updating, upgrading] ---- - -Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. - -### `backend encountered an error: libc++.so.1` - -Depending on your OS, you may encounter the following error when running `nargo prove` for the first time: - -```text -The backend encountered an error: "/home/codespace/.nargo/backends/acvm-backend-barretenberg/backend_binary: error while loading shared libraries: libc++.so.1: cannot open shared object file: No such file or directory\n" -``` - -Install the `libc++-dev` library with: - -```bash -sudo apt install libc++-dev -``` - -## ≥0.19 - -### Enforcing `compiler_version` - -From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. - -To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. - -## ≥0.14 - -The index of the [for loops](noir/concepts/control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: - -```rust -for i in 0..10 { - let i = i as Field; -} -``` - -## ≥v0.11.0 and Nargo backend - -From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: - -### `backend encountered an error` - -This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo prove -``` - -with your Noir program. - -This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. - -### `backend encountered an error: illegal instruction` - -On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. - -To fix the issue: - -1. Uninstall the existing backend - -```bash -nargo backend uninstall acvm-backend-barretenberg -``` - -You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. - -2. Reinstall a compatible version of the proving backend. - -If you are using the default barretenberg backend, simply run: - -``` -nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz -``` - -This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. - -The gzipped file is running [this bash script](https://github.com/noir-lang/barretenberg-js-binary/blob/master/run-bb-js.sh), where we need to gzip it as the Nargo currently expect the backend to be zipped up. - -Then run: - -``` -DESIRED_BINARY_VERSION=0.8.1 nargo info -``` - -This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. - -0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/_category_.json deleted file mode 100644 index 7da08f8a8c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Concepts", - "position": 0, - "collapsible": true, - "collapsed": true -} \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/assert.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/assert.md deleted file mode 100644 index bcff613a695..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/assert.md +++ /dev/null @@ -1,45 +0,0 @@ ---- -title: Assert Function -description: - Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or - comparison expression that follows to be true, and what happens if the expression is false at - runtime. -keywords: [Noir programming language, assert statement, predicate expression, comparison expression] -sidebar_position: 4 ---- - -Noir includes a special `assert` function which will explicitly constrain the predicate/comparison -expression that follows to be true. If this expression is false at runtime, the program will fail to -be proven. Example: - -```rust -fn main(x : Field, y : Field) { - assert(x == y); -} -``` - -> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. - -You can optionally provide a message to be logged when the assertion fails: - -```rust -assert(x == y, "x and y are not equal"); -``` - -Aside string literals, the optional message can be a format string or any other type supported as input for Noir's [print](../standard_library/logging.md) functions. This feature lets you incorporate runtime variables into your failed assertion logs: - -```rust -assert(x == y, f"Expected x == y, but got {x} == {y}"); -``` - -Using a variable as an assertion message directly: - -```rust -struct myStruct { - myField: Field -} - -let s = myStruct { myField: y }; -assert(s.myField == x, s); -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/comments.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/comments.md deleted file mode 100644 index b51a85f5c94..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/comments.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -title: Comments -description: - Learn how to write comments in Noir programming language. A comment is a line of code that is - ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments - are supported in Noir. -keywords: [Noir programming language, comments, single-line comments, multi-line comments] -sidebar_position: 10 ---- - -A comment is a line in your codebase which the compiler ignores, however it can be read by -programmers. - -Here is a single line comment: - -```rust -// This is a comment and is ignored -``` - -`//` is used to tell the compiler to ignore the rest of the line. - -Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. - -Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. - -```rust -/* - This is a block comment describing a complex function. -*/ -fn main(x : Field, y : pub Field) { - assert(x != y); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/control_flow.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/control_flow.md deleted file mode 100644 index 045d3c3a5f5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/control_flow.md +++ /dev/null @@ -1,77 +0,0 @@ ---- -title: Control Flow -description: - Learn how to use loops and if expressions in the Noir programming language. Discover the syntax - and examples for for loops and if-else statements. -keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] -sidebar_position: 2 ---- - -## If Expressions - -Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required -for the statement's conditional to be surrounded by parentheses. - -```rust -let a = 0; -let mut x: u32 = 0; - -if a == 0 { - if a != 0 { - x = 6; - } else { - x = 2; - } -} else { - x = 5; - assert(x == 5); -} -assert(x == 2); -``` - -## Loops - -Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple -times. - -The following block of code between the braces is run 10 times. - -```rust -for i in 0..10 { - // do something -} -``` - -The index for loops is of type `u64`. - -### Break and Continue - -In unconstrained code, `break` and `continue` are also allowed in `for` loops. These are only allowed -in unconstrained code since normal constrained code requires that Noir knows exactly how many iterations -a loop may have. `break` and `continue` can be used like so: - -```rust -for i in 0 .. 10 { - println("Iteration start") - - if i == 2 { - continue; - } - - if i == 5 { - break; - } - - println(i); -} -println("Loop end") -``` - -When used, `break` will end the current loop early and jump to the statement after the for loop. In the example -above, the `break` will stop the loop and jump to the `println("Loop end")`. - -`continue` will stop the current iteration of the loop, and jump to the start of the next iteration. In the example -above, `continue` will jump to `println("Iteration start")` when used. Note that the loop continues as normal after this. -The iteration variable `i` is still increased by one as normal when `continue` is used. - -`break` and `continue` cannot currently be used to jump out of more than a single loop at a time. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_bus.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_bus.md deleted file mode 100644 index e54fc861257..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_bus.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Data Bus -sidebar_position: 13 ---- -**Disclaimer** this feature is experimental, do not use it! - -The data bus is an optimization that the backend can use to make recursion more efficient. -In order to use it, you must define some inputs of the program entry points (usually the `main()` -function) with the `call_data` modifier, and the return values with the `return_data` modifier. -These modifiers are incompatible with `pub` and `mut` modifiers. - -## Example - -```rust -fn main(mut x: u32, y: call_data u32, z: call_data [u32;4] ) -> return_data u32 { - let a = z[x]; - a+y -} -``` - -As a result, both call_data and return_data will be treated as private inputs and encapsulated into a read-only array each, for the backend to process. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/arrays.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/arrays.md deleted file mode 100644 index 9b02d52e8a8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/arrays.md +++ /dev/null @@ -1,253 +0,0 @@ ---- -title: Arrays -description: - Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. -keywords: - [ - noir, - array type, - methods, - examples, - indexing, - ] -sidebar_position: 4 ---- - -An array is one way of grouping together values into one compound type. Array types can be inferred -or explicitly specified via the syntax `[; ]`: - -```rust -fn main(x : Field, y : Field) { - let my_arr = [x, y]; - let your_arr: [Field; 2] = [x, y]; -} -``` - -Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. - -Array elements can be accessed using indexing: - -```rust -fn main() { - let a = [1, 2, 3, 4, 5]; - - let first = a[0]; - let second = a[1]; -} -``` - -All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group -a `Field` value and a `u8` value together for example. - -You can write mutable arrays, like: - -```rust -fn main() { - let mut arr = [1, 2, 3, 4, 5]; - assert(arr[0] == 1); - - arr[0] = 42; - assert(arr[0] == 42); -} -``` - -You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. - -```rust -let array: [Field; 32] = [0; 32]; -``` - -Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices.mdx), you can just call `as_slice` on your array: - -```rust -let array: [Field; 32] = [0; 32]; -let sl = array.as_slice() -``` - -You can define multidimensional arrays: - -```rust -let array : [[Field; 2]; 2]; -let element = array[0][0]; -``` - -However, multidimensional slices are not supported. For example, the following code will error at compile time: - -```rust -let slice : [[Field]] = &[]; -``` - -## Types - -You can create arrays of primitive types or structs. There is not yet support for nested arrays -(arrays of arrays) or arrays of structs that contain arrays. - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for arrays. -Each of these functions are located within the generic impl `impl [T; N] {`. -So anywhere `self` appears, it refers to the variable `self: [T; N]`. - -### len - -Returns the length of an array - -```rust -fn len(self) -> Field -``` - -example - -```rust -fn main() { - let array = [42, 42]; - assert(array.len() == 2); -} -``` - -### sort - -Returns a new sorted array. The original array remains untouched. Notice that this function will -only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting -logic it uses internally is optimized specifically for these values. If you need a sort function to -sort any type, you should use the function `sort_via` described below. - -```rust -fn sort(self) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32]; - let sorted = arr.sort(); - assert(sorted == [32, 42]); -} -``` - -### sort_via - -Sorts the array with a custom comparison function - -```rust -fn sort_via(self, ordering: fn(T, T) -> bool) -> [T; N] -``` - -example - -```rust -fn main() { - let arr = [42, 32] - let sorted_ascending = arr.sort_via(|a, b| a <= b); - assert(sorted_ascending == [32, 42]); // verifies - - let sorted_descending = arr.sort_via(|a, b| a >= b); - assert(sorted_descending == [32, 42]); // does not verify -} -``` - -### map - -Applies a function to each element of the array, returning a new array containing the mapped elements. - -```rust -fn map(self, f: fn(T) -> U) -> [U; N] -``` - -example - -```rust -let a = [1, 2, 3]; -let b = a.map(|a| a * 2); // b is now [2, 4, 6] -``` - -### fold - -Applies a function to each element of the array, returning the final accumulated value. The first -parameter is the initial value. - -```rust -fn fold(self, mut accumulator: U, f: fn(U, T) -> U) -> U -``` - -This is a left fold, so the given function will be applied to the accumulator and first element of -the array, then the second, and so on. For a given call the expected result would be equivalent to: - -```rust -let a1 = [1]; -let a2 = [1, 2]; -let a3 = [1, 2, 3]; - -let f = |a, b| a - b; -a1.fold(10, f) //=> f(10, 1) -a2.fold(10, f) //=> f(f(10, 1), 2) -a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) -``` - -example: - -```rust - -fn main() { - let arr = [2, 2, 2, 2, 2]; - let folded = arr.fold(0, |a, b| a + b); - assert(folded == 10); -} - -``` - -### reduce - -Same as fold, but uses the first element as starting element. - -```rust -fn reduce(self, f: fn(T, T) -> T) -> T -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let reduced = arr.reduce(|a, b| a + b); - assert(reduced == 10); -} -``` - -### all - -Returns true if all the elements satisfy the given predicate - -```rust -fn all(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 2]; - let all = arr.all(|a| a == 2); - assert(all); -} -``` - -### any - -Returns true if any of the elements satisfy the given predicate - -```rust -fn any(self, predicate: fn(T) -> bool) -> bool -``` - -example: - -```rust -fn main() { - let arr = [2, 2, 2, 2, 5]; - let any = arr.any(|a| a == 5); - assert(any); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/booleans.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/booleans.md deleted file mode 100644 index 2507af710e7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/booleans.md +++ /dev/null @@ -1,28 +0,0 @@ ---- -title: Booleans -description: - Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. -keywords: - [ - noir, - boolean type, - methods, - examples, - logical operations, - ] -sidebar_position: 2 ---- - - -The `bool` type in Noir has two possible values: `true` and `false`: - -```rust -fn main() { - let t = true; - let f: bool = false; -} -``` - -The boolean type is most commonly used in conditionals like `if` expressions and `assert` -statements. More about conditionals is covered in the [Control Flow](../control_flow.md) and -[Assert Function](../assert.md) sections. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/fields.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/fields.md deleted file mode 100644 index a10a4810788..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/fields.md +++ /dev/null @@ -1,192 +0,0 @@ ---- -title: Fields -description: - Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. -keywords: - [ - noir, - field type, - methods, - examples, - best practices, - ] -sidebar_position: 0 ---- - -The field type corresponds to the native field type of the proving backend. - -The size of a Noir field depends on the elliptic curve's finite field for the proving backend -adopted. For example, a field would be a 254-bit integer when paired with the default backend that -spans the Grumpkin curve. - -Fields support integer arithmetic and are often used as the default numeric type in Noir: - -```rust -fn main(x : Field, y : Field) { - let z = x + y; -} -``` - -`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new -private value `z` constrained to be equal to `x + y`. - -If proving efficiency is of priority, fields should be used as a default for solving problems. -Smaller integer types (e.g. `u64`) incur extra range constraints. - -## Methods - -After declaring a Field, you can use these common methods on it: - -### to_le_bits - -Transforms the field into an array of bits, Little Endian. - -```rust -fn to_le_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_le_bits(32); -} -``` - -### to_be_bits - -Transforms the field into an array of bits, Big Endian. - -```rust -fn to_be_bits(_x : Field, _bit_size: u32) -> [u1] -``` - -example: - -```rust -fn main() { - let field = 2; - let bits = field.to_be_bits(32); -} -``` - -### to_le_bytes - -Transforms into an array of bytes, Little Endian - -```rust -fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_le_bytes(4); -} -``` - -### to_be_bytes - -Transforms into an array of bytes, Big Endian - -```rust -fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let bytes = field.to_be_bytes(4); -} -``` - -### to_le_radix - -Decomposes into a vector over the specified base, Little Endian - -```rust -fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_le_radix(256, 4); -} -``` - -### to_be_radix - -Decomposes into a vector over the specified base, Big Endian - -```rust -fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] -``` - -example: - -```rust -fn main() { - let field = 2; - let radix = field.to_be_radix(256, 4); -} -``` - -### pow_32 - -Returns the value to the power of the specified exponent - -```rust -fn pow_32(self, exponent: Field) -> Field -``` - -example: - -```rust -fn main() { - let field = 2 - let pow = field.pow_32(4); - assert(pow == 16); -} -``` - -### assert_max_bit_size - -Adds a constraint to specify that the field can be represented with `bit_size` number of bits - -```rust -fn assert_max_bit_size(self, bit_size: u32) -``` - -example: - -```rust -fn main() { - let field = 2 - field.assert_max_bit_size(32); -} -``` - -### sgn0 - -Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ \{0, ..., p-1\} is even, otherwise sgn0(x mod p) = 1. - -```rust -fn sgn0(self) -> u1 -``` - - -### lt - -Returns true if the field is less than the other field - -```rust -pub fn lt(self, another: Field) -> bool -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/function_types.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/function_types.md deleted file mode 100644 index f6121af17e2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/function_types.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Function types -sidebar_position: 10 ---- - -Noir supports higher-order functions. The syntax for a function type is as follows: - -```rust -fn(arg1_type, arg2_type, ...) -> return_type -``` - -Example: - -```rust -fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field - assert(f() == 100); -} - -fn main() { - assert_returns_100(|| 100); // ok - assert_returns_100(|| 150); // fails -} -``` - -A function type also has an optional capture environment - this is necessary to support closures. -See [Lambdas](../lambdas.md) for more details. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/index.md deleted file mode 100644 index 357813c147a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/index.md +++ /dev/null @@ -1,110 +0,0 @@ ---- -title: Data Types -description: - Get a clear understanding of the two categories of Noir data types - primitive types and compound - types. Learn about their characteristics, differences, and how to use them in your Noir - programming. -keywords: - [ - noir, - data types, - primitive types, - compound types, - private types, - public types, - ] ---- - -Every value in Noir has a type, which determines which operations are valid for it. - -All values in Noir are fundamentally composed of `Field` elements. For a more approachable -developing experience, abstractions are added on top to introduce different data types in Noir. - -Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound -types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or -public. - -## Private & Public Types - -A **private value** is known only to the Prover, while a **public value** is known by both the -Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All -primitive types (including individual fields of compound types) in Noir are private by default, and -can be marked public when certain values are intended to be revealed to the Verifier. - -> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once -> the proofs are verified on-chain the values can be considered known to everyone that has access to -> that blockchain. - -Public data types are treated no differently to private types apart from the fact that their values -will be revealed in proofs generated. Simply changing the value of a public type will not change the -circuit (where the same goes for changing values of private types as well). - -_Private values_ are also referred to as _witnesses_ sometimes. - -> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different -> meaning than when applied to a function (e.g. `pub fn foo() {}`). -> -> The former is a visibility modifier for the Prover to interpret if a value should be made known to -> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a -> function should be made accessible to external Noir programs like in other languages. - -### pub Modifier - -All data types in Noir are private by default. Types are explicitly declared as public using the -`pub` modifier: - -```rust -fn main(x : Field, y : pub Field) -> pub Field { - x + y -} -``` - -In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note -that visibility is handled **per variable**, so it is perfectly valid to have one input that is -private and another that is public. - -> **Note:** Public types can only be declared through parameters on `main`. - -## Type Aliases - -A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: - -```rust -type Id = u8; - -fn main() { - let id: Id = 1; - let zero: u8 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can also be used with [generics](../generics.md): - -```rust -type Id = Size; - -fn main() { - let id: Id = 1; - let zero: u32 = 0; - assert(zero + 1 == id); -} -``` - -Type aliases can even refer to other aliases. An error will be issued if they form a cycle: - -```rust -// Ok! -type A = B; -type B = Field; - -type Bad1 = Bad2; - -// error: Dependency cycle found -type Bad2 = Bad1; -// ^^^^^^^^^^^ 'Bad2' recursively depends on itself: Bad2 -> Bad1 -> Bad2 -``` - -### BigInt - -You can achieve BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/integers.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/integers.md deleted file mode 100644 index a1d59bf3166..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/integers.md +++ /dev/null @@ -1,156 +0,0 @@ ---- -title: Integers -description: Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. -keywords: [noir, integer types, methods, examples, arithmetic] -sidebar_position: 1 ---- - -An integer type is a range constrained field type. -The Noir frontend supports both unsigned and signed integer types. -The allowed sizes are 1, 8, 16, 32 and 64 bits. - -:::info - -When an integer is defined in Noir without a specific type, it will default to `Field`. - -The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. - -::: - -## Unsigned Integers - -An unsigned integer type is specified first with the letter `u` (indicating its unsigned nature) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: u8 = 1; - let y: u8 = 1; - let z = x + y; - assert (z == 2); -} -``` - -The bit size determines the maximum value the integer type can store. For example, a `u8` variable can store a value in the range of 0 to 255 (i.e. $\\2^{8}-1\\$). - -## Signed Integers - -A signed integer type is specified first with the letter `i` (which stands for integer) followed by its bit size (e.g. `8`): - -```rust -fn main() { - let x: i8 = -1; - let y: i8 = -1; - let z = x + y; - assert (z == -2); -} -``` - -The bit size determines the maximum and minimum range of value the integer type can store. For example, an `i8` variable can store a value in the range of -128 to 127 (i.e. $\\-2^{7}\\$ to $\\2^{7}-1\\$). - -## 128 bits Unsigned Integers - -The built-in structure `U128` allows you to use 128-bit unsigned integers almost like a native integer type. However, there are some differences to keep in mind: -- You cannot cast between a native integer and `U128` -- There is a higher performance cost when using `U128`, compared to a native type. - -Conversion between unsigned integer types and U128 are done through the use of `from_integer` and `to_integer` functions. `from_integer` also accepts the `Field` type as input. - -```rust -fn main() { - let x = U128::from_integer(23); - let y = U128::from_hex("0x7"); - let z = x + y; - assert(z.to_integer() == 30); -} -``` - -`U128` is implemented with two 64 bits limbs, representing the low and high bits, which explains the performance cost. You should expect `U128` to be twice more costly for addition and four times more costly for multiplication. -You can construct a U128 from its limbs: -```rust -fn main(x: u64, y: u64) { - let x = U128::from_u64s_be(x,y); - assert(z.hi == x as Field); - assert(z.lo == y as Field); -} -``` - -Note that the limbs are stored as Field elements in order to avoid unnecessary conversions. -Apart from this, most operations will work as usual: - -```rust -fn main(x: U128, y: U128) { - // multiplication - let c = x * y; - // addition and subtraction - let c = c - x + y; - // division - let c = x / y; - // bit operation; - let c = x & y | y; - // bit shift - let c = x << y; - // comparisons; - let c = x < y; - let c = x == y; -} -``` - -## Overflows - -Computations that exceed the type boundaries will result in overflow errors. This happens with both signed and unsigned integers. For example, attempting to prove: - -```rust -fn main(x: u8, y: u8) { - let z = x + y; -} -``` - -With: - -```toml -x = "255" -y = "1" -``` - -Would result in: - -``` -$ nargo execute -error: Assertion failed: 'attempt to add with overflow' -┌─ ~/src/main.nr:9:13 -│ -│ let z = x + y; -│ ----- -│ -= Call stack: - ... -``` - -A similar error would happen with signed integers: - -```rust -fn main() { - let x: i8 = -118; - let y: i8 = -11; - let z = x + y; -} -``` - -### Wrapping methods - -Although integer overflow is expected to error, some use-cases rely on wrapping. For these use-cases, the standard library provides `wrapping` variants of certain common operations: - -```rust -fn wrapping_add(x: T, y: T) -> T; -fn wrapping_sub(x: T, y: T) -> T; -fn wrapping_mul(x: T, y: T) -> T; -``` - -Example of how it is used: - -```rust - -fn main(x: u8, y: u8) -> pub u8 { - std::wrapping_add(x, y) -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/references.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/references.md deleted file mode 100644 index a5293d11cfb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/references.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -title: References -sidebar_position: 9 ---- - -Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. - -Example: - -```rust -fn main() { - let mut x = 2; - - // you can reference x as &mut and pass it to multiplyBy2 - multiplyBy2(&mut x); -} - -// you can access &mut here -fn multiplyBy2(x: &mut Field) { - // and dereference it with * - *x = *x * 2; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/slices.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/slices.mdx deleted file mode 100644 index dff08d63ffb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/slices.mdx +++ /dev/null @@ -1,193 +0,0 @@ ---- -title: Slices -description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. -keywords: [noir, slice type, methods, examples, subarrays] -sidebar_position: 5 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. - -```rust -fn main() -> pub u32 { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -To write a slice literal, use a preceeding ampersand as in: `&[0; 2]` or -`&[1, 2, 3]`. - -It is important to note that slices are not references to arrays. In Noir, -`&[..]` is more similar to an immutable, growable vector. - -View the corresponding test file [here][test-file]. - -[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr - -## Methods - -For convenience, the STD provides some ready-to-use, common methods for slices: - -### push_back - -Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. - -```rust -fn push_back(_self: [T], _elem: T) -> [T] -``` - -example: - -```rust -fn main() -> pub Field { - let mut slice: [Field] = &[0; 2]; - - let mut new_slice = slice.push_back(6); - new_slice.len() -} -``` - -View the corresponding test file [here][test-file]. - -### push_front - -Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. - -```rust -fn push_front(_self: Self, _elem: T) -> Self -``` - -Example: - -```rust -let mut new_slice: [Field] = &[]; -new_slice = new_slice.push_front(20); -assert(new_slice[0] == 20); // returns true -``` - -View the corresponding test file [here][test-file]. - -### pop_front - -Returns a tuple of two items, the first element of the array and the rest of the array. - -```rust -fn pop_front(_self: Self) -> (T, Self) -``` - -Example: - -```rust -let (first_elem, rest_of_slice) = slice.pop_front(); -``` - -View the corresponding test file [here][test-file]. - -### pop_back - -Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. - -```rust -fn pop_back(_self: Self) -> (Self, T) -``` - -Example: - -```rust -let (popped_slice, last_elem) = slice.pop_back(); -``` - -View the corresponding test file [here][test-file]. - -### append - -Loops over a slice and adds it to the end of another. - -```rust -fn append(mut self, other: Self) -> Self -``` - -Example: - -```rust -let append = &[1, 2].append(&[3, 4, 5]); -``` - -### insert - -Inserts an element at a specified index and shifts all following elements by 1. - -```rust -fn insert(_self: Self, _index: Field, _elem: T) -> Self -``` - -Example: - -```rust -new_slice = rest_of_slice.insert(2, 100); -assert(new_slice[2] == 100); -``` - -View the corresponding test file [here][test-file]. - -### remove - -Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. - -```rust -fn remove(_self: Self, _index: Field) -> (Self, T) -``` - -Example: - -```rust -let (remove_slice, removed_elem) = slice.remove(3); -``` - -### len - -Returns the length of a slice - -```rust -fn len(self) -> Field -``` - -Example: - -```rust -fn main() { - let slice = &[42, 42]; - assert(slice.len() == 2); -} -``` - -### as_array - -Converts this slice into an array. - -Make sure to specify the size of the resulting array. -Panics if the resulting array length is different than the slice's length. - -```rust -fn as_array(self) -> [T; N] -``` - -Example: - -```rust -fn main() { - let slice = &[5, 6]; - - // Always specify the length of the resulting array! - let array: [Field; 2] = slice.as_array(); - - assert(array[0] == slice[0]); - assert(array[1] == slice[1]); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/strings.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/strings.md deleted file mode 100644 index 1fdee42425e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/strings.md +++ /dev/null @@ -1,79 +0,0 @@ ---- -title: Strings -description: - Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. -keywords: - [ - noir, - string type, - methods, - examples, - concatenation, - ] -sidebar_position: 3 ---- - - -The string type is a fixed length value defined with `str`. - -You can use strings in `assert()` functions or print them with -`println()`. See more about [Logging](../../standard_library/logging.md). - -```rust - -fn main(message : pub str<11>, hex_as_string : str<4>) { - println(message); - assert(message == "hello world"); - assert(hex_as_string == "0x41"); -} -``` - -You can convert a `str` to a byte array by calling `as_bytes()` -or a vector by calling `as_bytes_vec()`. - -```rust -fn main() { - let message = "hello world"; - let message_bytes = message.as_bytes(); - let mut message_vec = message.as_bytes_vec(); - assert(message_bytes.len() == 11); - assert(message_bytes[0] == 104); - assert(message_bytes[0] == message_vec.get(0)); -} -``` - -## Escape characters - -You can use escape characters for your strings: - -| Escape Sequence | Description | -|-----------------|-----------------| -| `\r` | Carriage Return | -| `\n` | Newline | -| `\t` | Tab | -| `\0` | Null Character | -| `\"` | Double Quote | -| `\\` | Backslash | - -Example: - -```rust -let s = "Hello \"world" // prints "Hello "world" -let s = "hey \tyou"; // prints "hey you" -``` - -## Raw strings - -A raw string begins with the letter `r` and is optionally delimited by a number of hashes `#`. - -Escape characters are *not* processed within raw strings. All contents are interpreted literally. - -Example: - -```rust -let s = r"Hello world"; -let s = r#"Simon says "hello world""#; - -// Any number of hashes may be used (>= 1) as long as the string also terminates with the same number of hashes -let s = r#####"One "#, Two "##, Three "###, Four "####, Five will end the string."#####; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/structs.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/structs.md deleted file mode 100644 index dbf68c99813..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/structs.md +++ /dev/null @@ -1,70 +0,0 @@ ---- -title: Structs -description: - Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. -keywords: - [ - noir, - struct type, - methods, - examples, - data structures, - ] -sidebar_position: 8 ---- - -A struct also allows for grouping multiple values of different types. Unlike tuples, we can also -name each field. - -> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the -> field type of Noir. - -Defining a struct requires giving it a name and listing each field within as `: ` pairs: - -```rust -struct Animal { - hands: Field, - legs: Field, - eyes: u8, -} -``` - -An instance of a struct can then be created with actual values in `: ` pairs in any -order. Struct fields are accessible using their given names: - -```rust -fn main() { - let legs = 4; - - let dog = Animal { - eyes: 2, - hands: 0, - legs, - }; - - let zero = dog.hands; -} -``` - -Structs can also be destructured in a pattern, binding each field to a new variable: - -```rust -fn main() { - let Animal { hands, legs: feet, eyes } = get_octopus(); - - let ten = hands + feet + eyes as u8; -} - -fn get_octopus() -> Animal { - let octopus = Animal { - hands: 0, - legs: 8, - eyes: 2, - }; - - octopus -} -``` - -The new variables can be bound with names different from the original struct field names, as -showcased in the `legs --> feet` binding in the example above. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/tuples.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/tuples.md deleted file mode 100644 index 2ec5c9c4113..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/data_types/tuples.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -title: Tuples -description: - Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. -keywords: - [ - noir, - tuple type, - methods, - examples, - multi-value containers, - ] -sidebar_position: 7 ---- - -A tuple collects multiple values like an array, but with the added ability to collect values of -different types: - -```rust -fn main() { - let tup: (u8, u64, Field) = (255, 500, 1000); -} -``` - -One way to access tuple elements is via destructuring using pattern matching: - -```rust -fn main() { - let tup = (1, 2); - - let (one, two) = tup; - - let three = one + two; -} -``` - -Another way to access tuple elements is via direct member access, using a period (`.`) followed by -the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to -the second and so on: - -```rust -fn main() { - let tup = (5, 6, 7, 8); - - let five = tup.0; - let eight = tup.3; -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/functions.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/functions.md deleted file mode 100644 index f656cdfd97a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/functions.md +++ /dev/null @@ -1,226 +0,0 @@ ---- -title: Functions -description: - Learn how to declare functions and methods in Noir, a programming language with Rust semantics. - This guide covers parameter declaration, return types, call expressions, and more. -keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] -sidebar_position: 1 ---- - -Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. - -To declare a function the `fn` keyword is used. - -```rust -fn foo() {} -``` - -By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: - -```rust -pub fn foo() {} -``` - -You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: - -```rust -pub(crate) fn foo() {} //foo can only be called within its crate -``` - -All parameters in a function must have a type and all types are known at compile time. The parameter -is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. - -```rust -fn foo(x : Field, y : Field){} -``` - -The return type of a function can be stated by using the `->` arrow notation. The function below -states that the foo function must return a `Field`. If the function returns no value, then the arrow -is omitted. - -```rust -fn foo(x : Field, y : Field) -> Field { - x + y -} -``` - -Note that a `return` keyword is unneeded in this case - the last expression in a function's body is -returned. - -## Main function - -If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: - -```rust -fn main(x : Field) // this is fine: passing a Field -fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time -fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 -fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 - -fn main(x : Vec) // can't compile, has variable size -fn main(x : [Field]) // can't compile, has variable size -fn main(....// i think you got it by now -``` - -Keep in mind [tests](../../tooling/testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: - -```rust -fn main(x : [Field]) { - assert(x[0] == 1); -} - -#[test] -fn test_one() { - main(&[1, 2]); -} -``` - -```bash -$ nargo test -[testing] Running 1 test functions -[testing] Testing test_one... ok -[testing] All tests passed - -$ nargo check -The application panicked (crashed). -Message: Cannot have variable sized arrays as a parameter to main -``` - -## Call Expressions - -Calling a function in Noir is executed by using the function name and passing in the necessary -arguments. - -Below we show how to call the `foo` function from the `main` function using a call expression: - -```rust -fn main(x : Field, y : Field) { - let z = foo(x); -} - -fn foo(x : Field) -> Field { - x + x -} -``` - -## Methods - -You can define methods in Noir on any struct type in scope. - -```rust -struct MyStruct { - foo: Field, - bar: Field, -} - -impl MyStruct { - fn new(foo: Field) -> MyStruct { - MyStruct { - foo, - bar: 2, - } - } - - fn sum(self) -> Field { - self.foo + self.bar - } -} - -fn main() { - let s = MyStruct::new(40); - assert(s.sum() == 42); -} -``` - -Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as -follows: - -```rust -assert(MyStruct::sum(s) == 42); -``` - -It is also possible to specialize which method is chosen depending on the [generic](./generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: - -```rust -struct Foo {} - -impl Foo { - fn foo(self) -> Field { 1 } -} - -impl Foo { - fn foo(self) -> Field { 2 } -} - -fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; - assert(f1.foo() + f2.foo() == 3); -} -``` - -Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. - -```rust -// Including this impl in the same project as the above snippet would -// cause an overlapping impls error -impl Foo { - fn foo(self) -> Field { 3 } -} -``` - -## Lambdas - -Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -See [Lambdas](./lambdas.md) for more details. - -## Attributes - -Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. - -Supported attributes include: - -- **builtin**: the function is implemented by the compiler, for efficiency purposes. -- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` -- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details -- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./unconstrained.md) and [NoirJS](../../reference/NoirJS/noir_js/index.md) for more details. -- **test**: mark the function as unit tests. See [Tests](../../tooling/testing.md) for more details - -### Field Attribute - -The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. -The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. -As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. - -Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. - -```rust -#[field(bn254)] -fn foo() -> u32 { - 1 -} - -#[field(23)] -fn foo() -> u32 { - 2 -} - -// This commented code would not compile as foo would be defined twice because it is the same field as bn254 -// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] -// fn foo() -> u32 { -// 2 -// } - -#[field(bls12_381)] -fn foo() -> u32 { - 3 -} -``` - -If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/generics.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/generics.md deleted file mode 100644 index 0c1c27a2221..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/generics.md +++ /dev/null @@ -1,106 +0,0 @@ ---- -title: Generics -description: Learn how to use Generics in Noir -keywords: [Noir, Rust, generics, functions, structs] -sidebar_position: 7 ---- - -Generics allow you to use the same functions with multiple different concrete data types. You can -read more about the concept of generics in the Rust documentation -[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). - -Here is a trivial example showing the identity function that supports any type. In Rust, it is -common to refer to the most general type as `T`. We follow the same convention in Noir. - -```rust -fn id(x: T) -> T { - x -} -``` - -## In Structs - -Generics are useful for specifying types in structs. For example, we can specify that a field in a -struct will be of a certain generic type. In this case `value` is of type `T`. - -```rust -struct RepeatedValue { - value: T, - count: Field, -} - -impl RepeatedValue { - fn print(self) { - for _i in 0 .. self.count { - println(self.value); - } - } -} - -fn main() { - let repeated = RepeatedValue { value: "Hello!", count: 2 }; - repeated.print(); -} -``` - -The `print` function will print `Hello!` an arbitrary number of times, twice in this case. - -If we want to be generic over array lengths (which are type-level integers), we can use numeric -generics. Using these looks just like using regular generics, but these generics can resolve to -integers at compile-time, rather than resolving to types. Here's an example of a struct that is -generic over the size of the array it contains internally: - -```rust -struct BigInt { - limbs: [u32; N], -} - -impl BigInt { - // `N` is in scope of all methods in the impl - fn first(first: BigInt, second: BigInt) -> Self { - assert(first.limbs != second.limbs); - first - - fn second(first: BigInt, second: Self) -> Self { - assert(first.limbs != second.limbs); - second - } -} -``` - -## Calling functions on generic parameters - -Since a generic type `T` can represent any type, how can we call functions on the underlying type? -In other words, how can we go from "any type `T`" to "any type `T` that has certain methods available?" - -This is what [traits](../concepts/traits.md) are for in Noir. Here's an example of a function generic over -any type `T` that implements the `Eq` trait for equality: - -```rust -fn first_element_is_equal(array1: [T; N], array2: [T; N]) -> bool - where T: Eq -{ - if (array1.len() == 0) | (array2.len() == 0) { - true - } else { - array1[0] == array2[0] - } -} - -fn main() { - assert(first_element_is_equal([1, 2, 3], [1, 5, 6])); - - // We can use first_element_is_equal for arrays of any type - // as long as we have an Eq impl for the types we pass in - let array = [MyStruct::new(), MyStruct::new()]; - assert(array_eq(array, array, MyStruct::eq)); -} - -impl Eq for MyStruct { - fn eq(self, other: MyStruct) -> bool { - self.foo == other.foo - } -} -``` - -You can find more details on traits and trait implementations on the [traits page](../concepts/traits.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/globals.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/globals.md deleted file mode 100644 index 063a3d89248..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/globals.md +++ /dev/null @@ -1,72 +0,0 @@ ---- -title: Global Variables -description: - Learn about global variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, globals, global variables, constants] -sidebar_position: 8 ---- - -## Globals - - -Noir supports global variables. The global's type can be inferred by the compiler entirely: - -```rust -global N = 5; // Same as `global N: Field = 5` - -global TUPLE = (3, 2); - -fn main() { - assert(N == 5); - assert(N == TUPLE.0 + TUPLE.1); -} -``` - -:::info - -Globals can be defined as any expression, so long as they don't depend on themselves - otherwise there would be a dependency cycle! For example: - -```rust -global T = foo(T); // dependency error -``` - -::: - - -If they are initialized to a literal integer, globals can be used to specify an array's length: - -```rust -global N: Field = 2; - -fn main(y : [Field; N]) { - assert(y[0] == y[1]) -} -``` - -A global from another module can be imported or referenced externally like any other name: - -```rust -global N = 20; - -fn main() { - assert(my_submodule::N != N); -} - -mod my_submodule { - global N: Field = 10; -} -``` - -When a global is used, Noir replaces the name with its definition on each occurrence. -This means globals defined using function calls will repeat the call each time they're used: - -```rust -global RESULT = foo(); - -fn foo() -> [Field; 100] { ... } -``` - -This is usually fine since Noir will generally optimize any function call that does not -refer to a program input into a constant. It should be kept in mind however, if the called -function performs side-effects like `println`, as these will still occur on each use. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/lambdas.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/lambdas.md deleted file mode 100644 index be3c7e0b5ca..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/lambdas.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -title: Lambdas -description: Learn how to use anonymous functions in Noir programming language. -keywords: [Noir programming language, lambda, closure, function, anonymous function] -sidebar_position: 9 ---- - -## Introduction - -Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. - -```rust -let add_50 = |val| val + 50; -assert(add_50(100) == 150); -``` - -A block can be used as the body of a lambda, allowing you to declare local variables inside it: - -```rust -let cool = || { - let x = 100; - let y = 100; - x + y -} - -assert(cool() == 200); -``` - -## Closures - -Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: - -```rust -fn main() { - let x = 100; - let closure = || x + 150; - assert(closure() == 250); -} -``` - -## Passing closures to higher-order functions - -It may catch you by surprise that the following code fails to compile: - -```rust -fn foo(f: fn () -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // error :( -} -``` - -The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` -expects a regular function as an argument - those are incompatible. -:::note - -Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. - -E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. - -::: -The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - -in this example that's `(Field, Field)`. - -The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called -with closures with any environment, as well as with regular functions: - -```rust -fn foo(f: fn[Env]() -> Field) -> Field { - f() -} - -fn main() { - let (x, y) = (50, 50); - assert(foo(|| x + y) == 100); // compiles fine - assert(foo(|| 60) == 60); // compiles fine -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/mutability.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/mutability.md deleted file mode 100644 index fdeef6a87c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/mutability.md +++ /dev/null @@ -1,121 +0,0 @@ ---- -title: Mutability -description: - Learn about mutable variables in Noir. Discover how - to declare, modify, and use them in your programs. -keywords: [noir programming language, mutability in noir, mutable variables] -sidebar_position: 8 ---- - -Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned -to via an assignment expression. - -```rust -let x = 2; -x = 3; // error: x must be mutable to be assigned to - -let mut y = 3; -let y = 4; // OK -``` - -The `mut` modifier can also apply to patterns: - -```rust -let (a, mut b) = (1, 2); -a = 11; // error: a must be mutable to be assigned to -b = 12; // OK - -let mut (c, d) = (3, 4); -c = 13; // OK -d = 14; // OK - -// etc. -let MyStruct { x: mut y } = MyStruct { x: a }; -// y is now in scope -``` - -Note that mutability in noir is local and everything is passed by value, so if a called function -mutates its parameters then the parent function will keep the old value of the parameters. - -```rust -fn main() -> pub Field { - let x = 3; - helper(x); - x // x is still 3 -} - -fn helper(mut x: i32) { - x = 4; -} -``` - -## Non-local mutability - -Non-local mutability can be achieved through the mutable reference type `&mut T`: - -```rust -fn set_to_zero(x: &mut Field) { - *x = 0; -} - -fn main() { - let mut y = 42; - set_to_zero(&mut y); - assert(*y == 0); -} -``` - -When creating a mutable reference, the original variable being referred to (`y` in this -example) must also be mutable. Since mutable references are a reference type, they must -be explicitly dereferenced via `*` to retrieve the underlying value. Note that this yields -a copy of the value, so mutating this copy will not change the original value behind the -reference: - -```rust -fn main() { - let mut x = 1; - let x_ref = &mut x; - - let mut y = *x_ref; - let y_ref = &mut y; - - x = 2; - *x_ref = 3; - - y = 4; - *y_ref = 5; - - assert(x == 3); - assert(*x_ref == 3); - assert(y == 5); - assert(*y_ref == 5); -} -``` - -Note that types in Noir are actually deeply immutable so the copy that occurs when -dereferencing is only a conceptual copy - no additional constraints will occur. - -Mutable references can also be stored within structs. Note that there is also -no lifetime parameter on these unlike rust. This is because the allocated memory -always lasts the entire program - as if it were an array of one element. - -```rust -struct Foo { - x: &mut Field -} - -impl Foo { - fn incr(mut self) { - *self.x += 1; - } -} - -fn main() { - let foo = Foo { x: &mut 0 }; - foo.incr(); - assert(*foo.x == 1); -} -``` - -In general, you should avoid non-local & shared mutability unless it is needed. Sticking -to only local mutability will improve readability and potentially improve compiler optimizations as well. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/ops.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/ops.md deleted file mode 100644 index c35c36c38a9..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/ops.md +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Logical Operations -description: - Learn about the supported arithmetic and logical operations in the Noir programming language. - Discover how to perform operations on private input types, integers, and booleans. -keywords: - [ - Noir programming language, - supported operations, - arithmetic operations, - logical operations, - predicate operators, - bitwise operations, - short-circuiting, - backend, - ] -sidebar_position: 3 ---- - -# Operations - -## Table of Supported Operations - -| Operation | Description | Requirements | -| :-------- | :------------------------------------------------------------: | -------------------------------------: | -| + | Adds two private input types together | Types must be private input | -| - | Subtracts two private input types together | Types must be private input | -| \* | Multiplies two private input types together | Types must be private input | -| / | Divides two private input types together | Types must be private input | -| ^ | XOR two private input types together | Types must be integer | -| & | AND two private input types together | Types must be integer | -| \| | OR two private input types together | Types must be integer | -| \<\< | Left shift an integer by another integer amount | Types must be integer, shift must be u8 | -| >> | Right shift an integer by another integer amount | Types must be integer, shift must be u8 | -| ! | Bitwise not of a value | Type must be integer or boolean | -| \< | returns a bool if one value is less than the other | Upper bound must have a known bit size | -| \<= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | -| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | -| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | -| == | returns a bool if one value is equal to the other | Both types must not be constants | -| != | returns a bool if one value is not equal to the other | Both types must not be constants | - -### Predicate Operators - -`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. -This differs from the operations such as `+` where the operands are used in _computation_. - -### Bitwise Operations Example - -```rust -fn main(x : Field) { - let y = x as u32; - let z = y & y; -} -``` - -`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise -`&`. - -> `x & x` would not compile as `x` is a `Field` and not an integer type. - -### Logical Operators - -Noir has no support for the logical operators `||` and `&&`. This is because encoding the -short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can -use the bitwise operators `|` and `&` which operate identically for booleans, just without the -short-circuiting. - -```rust -let my_val = 5; - -let mut flag = 1; -if (my_val > 6) | (my_val == 0) { - flag = 0; -} -assert(flag == 1); - -if (my_val != 10) & (my_val < 50) { - flag = 0; -} -assert(flag == 0); -``` - -### Shorthand operators - -Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: - -```rust -let mut i = 0; -i = i + 1; -``` - -could be written as: - -```rust -let mut i = 0; -i += 1; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/oracles.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/oracles.md deleted file mode 100644 index aa380b5f7b8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/oracles.md +++ /dev/null @@ -1,31 +0,0 @@ ---- -title: Oracles -description: Dive into how Noir supports Oracles via RPC calls, and learn how to declare an Oracle in Noir with our comprehensive guide. -keywords: - - Noir - - Oracles - - RPC Calls - - Unconstrained Functions - - Programming - - Blockchain -sidebar_position: 6 ---- - -:::note - -This is an experimental feature that is not fully documented. If you notice any outdated information or potential improvements to this page, pull request contributions are very welcome: https://github.com/noir-lang/noir - -::: - -Noir has support for Oracles via RPC calls. This means Noir will make an RPC call and use the return value for proof generation. - -Since Oracles are not resolved by Noir, they are [`unconstrained` functions](./unconstrained.md) - -You can declare an Oracle through the `#[oracle()]` flag. Example: - -```rust -#[oracle(get_number_sequence)] -unconstrained fn get_number_sequence(_size: Field) -> [Field] {} -``` - -The timeout for when using an external RPC oracle resolver can be set with the `NARGO_FOREIGN_CALL_TIMEOUT` environment variable. This timeout is in units of milliseconds. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/shadowing.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/shadowing.md deleted file mode 100644 index 5ce6130d201..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/shadowing.md +++ /dev/null @@ -1,44 +0,0 @@ ---- -title: Shadowing -sidebar_position: 12 ---- - -Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. - -For example, the following function is valid in Noir: - -```rust -fn main() { - let x = 5; - - { - let x = x * 2; - assert (x == 10); - } - - assert (x == 5); -} -``` - -In this example, a variable x is first defined with the value 5. - -The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. - -When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. - -## Temporal mutability - -One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. - -```rust -fn main() { - let age = 30; - // age = age + 5; // Would error as `age` is immutable by default. - - let mut age = age + 5; // Temporarily mutates `age` with a new value. - - let age = age; // Locks `age`'s mutability again. - - assert (age == 35); -} -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/traits.md deleted file mode 100644 index df7cb9ebda0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/traits.md +++ /dev/null @@ -1,389 +0,0 @@ ---- -title: Traits -description: - Traits in Noir can be used to abstract out a common interface for functions across - several data types. -keywords: [noir programming language, traits, interfaces, generic, protocol] -sidebar_position: 14 ---- - -## Overview - -Traits in Noir are a useful abstraction similar to interfaces or protocols in other languages. Each trait defines -the interface of several methods contained within the trait. Types can then implement this trait by providing -implementations for these methods. For example in the program: - -```rust -struct Rectangle { - width: Field, - height: Field, -} - -impl Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -fn log_area(r: Rectangle) { - println(r.area()); -} -``` - -We have a function `log_area` to log the area of a `Rectangle`. Now how should we change the program if we want this -function to work on `Triangle`s as well?: - -```rust -struct Triangle { - width: Field, - height: Field, -} - -impl Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Making `log_area` generic over all types `T` would be invalid since not all types have an `area` method. Instead, we can -introduce a new `Area` trait and make `log_area` generic over all types `T` that implement `Area`: - -```rust -trait Area { - fn area(self) -> Field; -} - -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -We also need to explicitly implement `Area` for `Rectangle` and `Triangle`. We can do that by changing their existing -impls slightly. Note that the parameter types and return type of each of our `area` methods must match those defined -by the `Area` trait. - -```rust -impl Area for Rectangle { - fn area(self) -> Field { - self.width * self.height - } -} - -impl Area for Triangle { - fn area(self) -> Field { - self.width * self.height / 2 - } -} -``` - -Now we have a working program that is generic over any type of Shape that is used! Others can even use this program -as a library with their own types - such as `Circle` - as long as they also implement `Area` for these types. - -## Where Clauses - -As seen in `log_area` above, when we want to create a function or method that is generic over any type that implements -a trait, we can add a where clause to the generic function. - -```rust -fn log_area(shape: T) where T: Area { - println(shape.area()); -} -``` - -It is also possible to apply multiple trait constraints on the same variable at once by combining traits with the `+` -operator. Similarly, we can have multiple trait constraints by separating each with a comma: - -```rust -fn foo(elements: [T], thing: U) where - T: Default + Add + Eq, - U: Bar, -{ - let mut sum = T::default(); - - for element in elements { - sum += element; - } - - if sum == T::default() { - thing.bar(); - } -} -``` - -## Generic Implementations - -You can add generics to a trait implementation by adding the generic list after the `impl` keyword: - -```rust -trait Second { - fn second(self) -> Field; -} - -impl Second for (T, Field) { - fn second(self) -> Field { - self.1 - } -} -``` - -You can also implement a trait for every type this way: - -```rust -trait Debug { - fn debug(self); -} - -impl Debug for T { - fn debug(self) { - println(self); - } -} - -fn main() { - 1.debug(); -} -``` - -### Generic Trait Implementations With Where Clauses - -Where clauses can also be placed on trait implementations themselves to restrict generics in a similar way. -For example, while `impl Foo for T` implements the trait `Foo` for every type, `impl Foo for T where T: Bar` -will implement `Foo` only for types that also implement `Bar`. This is often used for implementing generic types. -For example, here is the implementation for array equality: - -```rust -impl Eq for [T; N] where T: Eq { - // Test if two arrays have the same elements. - // Because both arrays must have length N, we know their lengths already match. - fn eq(self, other: Self) -> bool { - let mut result = true; - - for i in 0 .. self.len() { - // The T: Eq constraint is needed to call == on the array elements here - result &= self[i] == other[i]; - } - - result - } -} -``` - -## Generic Traits - -Traits themselves can also be generic by placing the generic arguments after the trait name. These generics are in -scope of every item within the trait. - -```rust -trait Into { - // Convert `self` to type `T` - fn into(self) -> T; -} -``` - -When implementing generic traits the generic arguments of the trait must be specified. This is also true anytime -when referencing a generic trait (e.g. in a `where` clause). - -```rust -struct MyStruct { - array: [Field; 2], -} - -impl Into<[Field; 2]> for MyStruct { - fn into(self) -> [Field; 2] { - self.array - } -} - -fn as_array(x: T) -> [Field; 2] - where T: Into<[Field; 2]> -{ - x.into() -} - -fn main() { - let array = [1, 2]; - let my_struct = MyStruct { array }; - - assert_eq(as_array(my_struct), array); -} -``` - -## Trait Methods With No `self` - -A trait can contain any number of methods, each of which have access to the `Self` type which represents each type -that eventually implements the trait. Similarly, the `self` variable is available as well but is not required to be used. -For example, we can define a trait to create a default value for a type. This trait will need to return the `Self` type -but doesn't need to take any parameters: - -```rust -trait Default { - fn default() -> Self; -} -``` - -Implementing this trait can be done similarly to any other trait: - -```rust -impl Default for Field { - fn default() -> Field { - 0 - } -} - -struct MyType {} - -impl Default for MyType { - fn default() -> Field { - MyType {} - } -} -``` - -However, since there is no `self` parameter, we cannot call it via the method call syntax `object.method()`. -Instead, we'll need to refer to the function directly. This can be done either by referring to the -specific impl `MyType::default()` or referring to the trait itself `Default::default()`. In the later -case, type inference determines the impl that is selected. - -```rust -let my_struct = MyStruct::default(); - -let x: Field = Default::default(); -let result = x + Default::default(); -``` - -:::warning - -```rust -let _ = Default::default(); -``` - -If type inference cannot select which impl to use because of an ambiguous `Self` type, an impl will be -arbitrarily selected. This occurs most often when the result of a trait function call with no parameters -is unused. To avoid this, when calling a trait function with no `self` or `Self` parameters or return type, -always refer to it via the implementation type's namespace - e.g. `MyType::default()`. -This is set to change to an error in future Noir versions. - -::: - -## Default Method Implementations - -A trait can also have default implementations of its methods by giving a body to the desired functions. -Note that this body must be valid for all types that may implement the trait. As a result, the only -valid operations on `self` will be operations valid for any type or other operations on the trait itself. - -```rust -trait Numeric { - fn add(self, other: Self) -> Self; - - // Default implementation of double is (self + self) - fn double(self) -> Self { - self.add(self) - } -} -``` - -When implementing a trait with default functions, a type may choose to implement only the required functions: - -```rust -impl Numeric for Field { - fn add(self, other: Field) -> Field { - self + other - } -} -``` - -Or it may implement the optional methods as well: - -```rust -impl Numeric for u32 { - fn add(self, other: u32) -> u32 { - self + other - } - - fn double(self) -> u32 { - self * 2 - } -} -``` - -## Impl Specialization - -When implementing traits for a generic type it is possible to implement the trait for only a certain combination -of generics. This can be either as an optimization or because those specific generics are required to implement the trait. - -```rust -trait Sub { - fn sub(self, other: Self) -> Self; -} - -struct NonZero { - value: T, -} - -impl Sub for NonZero { - fn sub(self, other: Self) -> Self { - let value = self.value - other.value; - assert(value != 0); - NonZero { value } - } -} -``` - -## Overlapping Implementations - -Overlapping implementations are disallowed by Noir to ensure Noir's decision on which impl to select is never ambiguous. -This means if a trait `Foo` is already implemented -by a type `Bar` for all `T`, then we cannot also have a separate impl for `Bar` (or any other -type argument). Similarly, if there is an impl for all `T` such as `impl Debug for T`, we cannot create -any more impls to `Debug` for other types since it would be ambiguous which impl to choose for any given -method call. - -```rust -trait Trait {} - -// Previous impl defined here -impl Trait for (A, B) {} - -// error: Impl for type `(Field, Field)` overlaps with existing impl -impl Trait for (Field, Field) {} -``` - -## Trait Coherence - -Another restriction on trait implementations is coherence. This restriction ensures other crates cannot create -impls that may overlap with other impls, even if several unrelated crates are used as dependencies in the same -program. - -The coherence restriction is: to implement a trait, either the trait itself or the object type must be declared -in the crate the impl is in. - -In practice this often comes up when using types provided by libraries. If a library provides a type `Foo` that does -not implement a trait in the standard library such as `Default`, you may not `impl Default for Foo` in your own crate. -While restrictive, this prevents later issues or silent changes in the program if the `Foo` library later added its -own impl for `Default`. If you are a user of the `Foo` library in this scenario and need a trait not implemented by the -library your choices are to either submit a patch to the library or use the newtype pattern. - -### The Newtype Pattern - -The newtype pattern gets around the coherence restriction by creating a new wrapper type around the library type -that we cannot create `impl`s for. Since the new wrapper type is defined in our current crate, we can create -impls for any trait we need on it. - -```rust -struct Wrapper { - foo: some_library::Foo, -} - -impl Default for Wrapper { - fn default() -> Wrapper { - Wrapper { - foo: some_library::Foo::new(), - } - } -} -``` - -Since we have an impl for our own type, the behavior of this code will not change even if `some_library` is updated -to provide its own `impl Default for Foo`. The downside of this pattern is that it requires extra wrapping and -unwrapping of values when converting to and from the `Wrapper` and `Foo` types. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/unconstrained.md deleted file mode 100644 index 96f824c5e42..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/concepts/unconstrained.md +++ /dev/null @@ -1,99 +0,0 @@ ---- -title: Unconstrained Functions -description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." - -keywords: [Noir programming language, unconstrained, open] -sidebar_position: 5 ---- - -Unconstrained functions are functions which do not constrain any of the included computation and allow for non-deterministic computation. - -## Why? - -Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. - -Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. - -Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. - -A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. - -## Example - -An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. - -Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 -Backend circuit size: 3619 -``` - -A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the AND against 0xff. This saves us ~480 gates in total. - -```rust -fn main(num: u72) -> pub [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8)) as u8; - } - - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 -Backend circuit size: 3143 -``` - -Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. - -It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. - -We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: - -```rust -fn main(num: u72) -> pub [u8; 8] { - let out = u72_to_u8(num); - - let mut reconstructed_num: u72 = 0; - for i in 0..8 { - reconstructed_num += (out[i] as u72 << (56 - (8 * i))); - } - assert(num == reconstructed_num); - out -} - -unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { - let mut out: [u8; 8] = [0; 8]; - for i in 0..8 { - out[i] = (num >> (56 - (i * 8))) as u8; - } - out -} -``` - -``` -Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 -Backend circuit size: 2902 -``` - -This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). - -Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. - -## Break and Continue - -In addition to loops over runtime bounds, `break` and `continue` are also available in unconstrained code. See [break and continue](../concepts/control_flow.md#break-and-continue) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/_category_.json deleted file mode 100644 index 1debcfe7675..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Modules, Packages and Crates", - "position": 2, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/crates_and_packages.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/crates_and_packages.md deleted file mode 100644 index 95ee9f52ab2..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/crates_and_packages.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Crates and Packages -description: Learn how to use Crates and Packages in your Noir project -keywords: [Nargo, dependencies, package management, crates, package] -sidebar_position: 0 ---- - -## Crates - -A crate is the smallest amount of code that the Noir compiler considers at a time. -Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. - -### Crate Types - -A Noir crate can come in several forms: binaries, libraries or contracts. - -#### Binaries - -_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. - -#### Libraries - -_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. - -#### Contracts - -Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/noir-projects/noir-contracts/contracts). - -### Crate Root - -Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. - -## Packages - -A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. - -A package _must_ contain either a library or a binary crate, but not both. - -### Differences from Cargo Packages - -One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. - -In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/dependencies.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/dependencies.md deleted file mode 100644 index 24e02de08fe..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/dependencies.md +++ /dev/null @@ -1,124 +0,0 @@ ---- -title: Dependencies -description: - Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub - and use them easily in your project. -keywords: [Nargo, dependencies, GitHub, package management, versioning] -sidebar_position: 1 ---- - -Nargo allows you to upload packages to GitHub and use them as dependencies. - -## Specifying a dependency - -Specifying a dependency requires a tag to a specific commit and the git url to the url containing -the package. - -Currently, there are no requirements on the tag contents. If requirements are added, it would follow -semver 2.0 guidelines. - -> Note: Without a `tag` , there would be no versioning and dependencies would change each time you -> compile your project. - -For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: - -```toml -# Nargo.toml - -[dependencies] -ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} -``` - -If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: - -```toml -# Nargo.toml - -[dependencies] -easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "noir-contracts/contracts/easy_private_token_contract"} -``` - -## Specifying a local dependency - -You can also specify dependencies that are local to your machine. - -For example, this file structure has a library and binary crate - -```tree -├── binary_crate -│   ├── Nargo.toml -│   └── src -│   └── main.nr -└── lib_a - ├── Nargo.toml - └── src - └── lib.nr -``` - -Inside of the binary crate, you can specify: - -```toml -# Nargo.toml - -[dependencies] -lib_a = { path = "../lib_a" } -``` - -## Importing dependencies - -You can import a dependency to a Noir file using the following syntax. For example, to import the -ecrecover-noir library and local lib_a referenced above: - -```rust -use ecrecover; -use lib_a; -``` - -You can also import only the specific parts of dependency that you want to use, like so: - -```rust -use std::hash::sha256; -use std::scalar_mul::fixed_base_embedded_curve; -``` - -Lastly, as demonstrated in the -[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives.md#examples), you -can import multiple items in the same line by enclosing them in curly braces: - -```rust -use std::ec::tecurve::affine::{Curve, Point}; -``` - -We don't have a way to consume libraries from inside a [workspace](./workspaces.md) as external dependencies right now. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -## Dependencies of Dependencies - -Note that when you import a dependency, you also get access to all of the dependencies of that package. - -For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: - -```rust -use phy_vector; - -fn main(x : Field, y : pub Field) { - //... - let f = phy_vector::fraction::toFraction(true, 2, 1); - //... -} -``` - -## Available Libraries - -Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). - -Some libraries that are available today include: - -- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library -- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) -- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers -- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address -- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees -- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir -- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/modules.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/modules.md deleted file mode 100644 index ae822a1cff4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/modules.md +++ /dev/null @@ -1,105 +0,0 @@ ---- -title: Modules -description: - Learn how to organize your files using modules in Noir, following the same convention as Rust's - module system. Examples included. -keywords: [Noir, Rust, modules, organizing files, sub-modules] -sidebar_position: 2 ---- - -Noir's module system follows the same convention as the _newer_ version of Rust's module system. - -## Purpose of Modules - -Modules are used to organize files. Without modules all of your code would need to live in a single -file. In Noir, the compiler does not automatically scan all of your files to detect modules. This -must be done explicitly by the developer. - -## Examples - -### Importing a module in the crate root - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::hello_world(); -} -``` - -Filename : `src/foo.nr` - -```rust -fn from_foo() {} -``` - -In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module -declaration `mod foo` which prompts it to look for a foo.nr file. - -Visually this module hierarchy looks like the following : - -``` -crate - ├── main - │ - └── foo - └── from_foo - -``` - -### Importing a module throughout the tree - -All modules are accessible from the `crate::` namespace. - -``` -crate - ├── bar - ├── foo - └── main - -``` - -In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. - -### Sub-modules - -Filename : `src/main.nr` - -```rust -mod foo; - -fn main() { - foo::from_foo(); -} -``` - -Filename : `src/foo.nr` - -```rust -mod bar; -fn from_foo() {} -``` - -Filename : `src/foo/bar.nr` - -```rust -fn from_bar() {} -``` - -In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule -of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the -compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` - -Visually the module hierarchy looks as follows: - -``` -crate - ├── main - │ - └── foo - ├── from_foo - └── bar - └── from_bar -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/workspaces.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/workspaces.md deleted file mode 100644 index 513497f12bf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/modules_packages_crates/workspaces.md +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: Workspaces -sidebar_position: 3 ---- - -Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. - -Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. - -For a project with the following structure: - -```tree -├── crates -│ ├── a -│ │ ├── Nargo.toml -│ │ └── Prover.toml -│ │ └── src -│ │ └── main.nr -│ └── b -│ ├── Nargo.toml -│ └── Prover.toml -│ └── src -│ └── main.nr -│ -└── Nargo.toml -``` - -You can define a workspace in Nargo.toml like so: - -```toml -[workspace] -members = ["crates/a", "crates/b"] -default-member = "crates/a" -``` - -`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. - -`default-member` indicates which package various commands process by default. - -Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. - -Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/_category_.json deleted file mode 100644 index af04c0933fd..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Standard Library", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bigint.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bigint.md deleted file mode 100644 index 2bfdeec6631..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bigint.md +++ /dev/null @@ -1,122 +0,0 @@ ---- -title: Big Integers -description: How to use big integers from Noir standard library -keywords: - [ - Big Integer, - Noir programming language, - Noir libraries, - ] ---- - -The BigInt module in the standard library exposes some class of integers which do not fit (well) into a Noir native field. It implements modulo arithmetic, modulo a 'big' prime number. - -:::note - -The module can currently be considered as `Field`s with fixed modulo sizes used by a set of elliptic curves, in addition to just the native curve. [More work](https://github.com/noir-lang/noir/issues/510) is needed to achieve arbitrarily sized big integers. - -::: - -Currently 6 classes of integers (i.e 'big' prime numbers) are available in the module, namely: - -- BN254 Fq: Bn254Fq -- BN254 Fr: Bn254Fr -- Secp256k1 Fq: Secpk1Fq -- Secp256k1 Fr: Secpk1Fr -- Secp256r1 Fr: Secpr1Fr -- Secp256r1 Fq: Secpr1Fq - -Where XXX Fq and XXX Fr denote respectively the order of the base and scalar field of the (usual) elliptic curve XXX. -For instance the big integer 'Secpk1Fq' in the standard library refers to integers modulo $2^{256}-2^{32}-977$. - -Feel free to explore the source code for the other primes: - -```rust title="big_int_definition" showLineNumbers -struct BigInt { - pointer: u32, - modulus: u32, -} -``` -> Source code: noir_stdlib/src/bigint.nr#L14-L19 - - -## Example usage - -A common use-case is when constructing a big integer from its bytes representation, and performing arithmetic operations on it: - -```rust title="big_int_example" showLineNumbers -fn big_int_example(x: u8, y: u8) { - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - let b = Secpk1Fq::from_le_bytes(&[y, x, 9]); - let c = (a + b) * b / a; - let d = c.to_le_bytes(); - println(d[0]); -} -``` -> Source code: test_programs/execution_success/bigint/src/main.nr#L70-L78 - - -## Methods - -The available operations for each big integer are: - -### from_le_bytes - -Construct a big integer from its little-endian bytes representation. Example: - -```rust - // Construct a big integer from a slice of bytes - let a = Secpk1Fq::from_le_bytes(&[x, y, 0, 45, 2]); - // Construct a big integer from an array of 32 bytes - let a = Secpk1Fq::from_le_bytes_32([1;32]); - ``` - -Sure, here's the formatted version of the remaining methods: - -### to_le_bytes - -Return the little-endian bytes representation of a big integer. Example: - -```rust -let bytes = a.to_le_bytes(); -``` - -### add - -Add two big integers. Example: - -```rust -let sum = a + b; -``` - -### sub - -Subtract two big integers. Example: - -```rust -let difference = a - b; -``` - -### mul - -Multiply two big integers. Example: - -```rust -let product = a * b; -``` - -### div - -Divide two big integers. Note that division is field division and not euclidean division. Example: - -```rust -let quotient = a / b; -``` - -### eq - -Compare two big integers. Example: - -```rust -let are_equal = a == b; -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/black_box_fns.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/black_box_fns.md deleted file mode 100644 index d5694250f05..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/black_box_fns.md +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Black Box Functions -description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. -keywords: [noir, black box functions] ---- - -Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. - -The ACVM spec defines a set of blackbox functions which backends will be expected to implement. This allows backends to use optimized implementations of these constraints if they have them, however they may also fallback to less efficient naive implementations if not. - -## Function list - -Here is a list of the current black box functions: - -- [AES128](./cryptographic_primitives/ciphers.mdx#aes128) -- [SHA256](./cryptographic_primitives/hashes.mdx#sha256) -- [Schnorr signature verification](./cryptographic_primitives/schnorr.mdx) -- [Blake2s](./cryptographic_primitives/hashes.mdx#blake2s) -- [Blake3](./cryptographic_primitives/hashes.mdx#blake3) -- [Pedersen Hash](./cryptographic_primitives/hashes.mdx#pedersen_hash) -- [Pedersen Commitment](./cryptographic_primitives/hashes.mdx#pedersen_commitment) -- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification.mdx) -- [Embedded curve operations (MSM, addition, ...)](./cryptographic_primitives/embedded_curve_ops.mdx) -- AND -- XOR -- RANGE -- [Keccak256](./cryptographic_primitives/hashes.mdx#keccak256) -- [Recursive proof verification](./recursion.md) - -Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. - -You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/noir/blob/master/acvm-repo/acir/src/circuit/black_box_functions.rs). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bn254.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bn254.md deleted file mode 100644 index 3294f005dbb..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/bn254.md +++ /dev/null @@ -1,46 +0,0 @@ ---- -title: Bn254 Field Library ---- - -Noir provides a module in standard library with some optimized functions for bn254 Fr in `std::field::bn254`. - -## decompose - -```rust -fn decompose(x: Field) -> (Field, Field) {} -``` - -Decomposes a single field into two fields, low and high. The low field contains the lower 16 bytes of the input field and the high field contains the upper 16 bytes of the input field. Both field results are range checked to 128 bits. - - -## assert_gt - -```rust -fn assert_gt(a: Field, b: Field) {} -``` - -Asserts that a > b. This will generate less constraints than using `assert(gt(a, b))`. - -## assert_lt - -```rust -fn assert_lt(a: Field, b: Field) {} -``` - -Asserts that a < b. This will generate less constraints than using `assert(lt(a, b))`. - -## gt - -```rust -fn gt(a: Field, b: Field) -> bool {} -``` - -Returns true if a > b. - -## lt - -```rust -fn lt(a: Field, b: Field) -> bool {} -``` - -Returns true if a < b. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/boundedvec.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/boundedvec.md deleted file mode 100644 index 4349eab67c5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/boundedvec.md +++ /dev/null @@ -1,419 +0,0 @@ ---- -title: Bounded Vectors -keywords: [noir, vector, bounded vector, slice] -sidebar_position: 1 ---- - -A `BoundedVec` is a growable storage similar to a `Vec` except that it -is bounded with a maximum possible length. Unlike `Vec`, `BoundedVec` is not implemented -via slices and thus is not subject to the same restrictions slices are (notably, nested -slices - and thus nested vectors as well - are disallowed). - -Since a BoundedVec is backed by a normal array under the hood, growing the BoundedVec by -pushing an additional element is also more efficient - the length only needs to be increased -by one. - -For these reasons `BoundedVec` should generally be preferred over `Vec` when there -is a reasonable maximum bound that can be placed on the vector. - -Example: - -```rust -let mut vector: BoundedVec = BoundedVec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -assert(vector.max_len() == 10); -``` - -## Methods - -### new - -```rust -pub fn new() -> Self -``` - -Creates a new, empty vector of length zero. - -Since this container is backed by an array internally, it still needs an initial value -to give each element. To resolve this, each element is zeroed internally. This value -is guaranteed to be inaccessible unless `get_unchecked` is used. - -Example: - -```rust -let empty_vector: BoundedVec = BoundedVec::new(); -assert(empty_vector.len() == 0); -``` - -Note that whenever calling `new` the maximum length of the vector should always be specified -via a type signature: - -```rust title="new_example" showLineNumbers -fn foo() -> BoundedVec { - // Ok! MaxLen is specified with a type annotation - let v1: BoundedVec = BoundedVec::new(); - let v2 = BoundedVec::new(); - - // Ok! MaxLen is known from the type of foo's return value - v2 -} - -fn bad() { - let mut v3 = BoundedVec::new(); - - // Not Ok! We don't know if v3's MaxLen is at least 1, and the compiler often infers 0 by default. - v3.push(5); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L11-L27 - - -This defaulting of `MaxLen` (and numeric generics in general) to zero may change in future noir versions -but for now make sure to use type annotations when using bounded vectors. Otherwise, you will receive a constraint failure at runtime when the vec is pushed to. - -### get - -```rust -pub fn get(self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this -will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - let last = v.get(v.len() - 1); - assert(first != last); -} -``` - -### get_unchecked - -```rust -pub fn get_unchecked(self, index: u64) -> T { -``` - -Retrieves an element from the vector at the given index, starting from zero, without -performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, -it is unsafe! Use at your own risk! - -Example: - -```rust title="get_unchecked_example" showLineNumbers -fn sum_of_first_three(v: BoundedVec) -> u32 { - // Always ensure the length is larger than the largest - // index passed to get_unchecked - assert(v.len() > 2); - let first = v.get_unchecked(0); - let second = v.get_unchecked(1); - let third = v.get_unchecked(2); - first + second + third -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L54-L64 - - -### set - -```rust -pub fn set(&mut self: Self, index: u64, value: T) { -``` - -Writes an element to the vector at the given index, starting from zero. - -If the given index is equal to or greater than the length of the vector, this will issue a constraint failure. - -Example: - -```rust -fn foo(v: BoundedVec) { - let first = v.get(0); - assert(first != 42); - v.set(0, 42); - let new_first = v.get(0); - assert(new_first == 42); -} -``` - -### set_unchecked - -```rust -pub fn set_unchecked(&mut self: Self, index: u64, value: T) -> T { -``` - -Writes an element to the vector at the given index, starting from zero, without performing a bounds check. - -Since this function does not perform a bounds check on length before accessing the element, it is unsafe! Use at your own risk! - -Example: - -```rust title="set_unchecked_example" showLineNumbers -fn set_unchecked_example() { - let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([1, 2]); - - // Here we're safely writing within the valid range of `vec` - // `vec` now has the value [42, 2] - vec.set_unchecked(0, 42); - - // We can then safely read this value back out of `vec`. - // Notice that we use the checked version of `get` which would prevent reading unsafe values. - assert_eq(vec.get(0), 42); - - // We've now written past the end of `vec`. - // As this index is still within the maximum potential length of `v`, - // it won't cause a constraint failure. - vec.set_unchecked(2, 42); - println(vec); - - // This will write past the end of the maximum potential length of `vec`, - // it will then trigger a constraint failure. - vec.set_unchecked(5, 42); - println(vec); -} -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L67-L91 - - - -### push - -```rust -pub fn push(&mut self, elem: T) { -``` - -Pushes an element to the end of the vector. This increases the length -of the vector by one. - -Panics if the new length of the vector will be greater than the max length. - -Example: - -```rust title="bounded-vec-push-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - v.push(1); - v.push(2); - - // Panics with failed assertion "push out of bounds" - v.push(3); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L95-L103 - - -### pop - -```rust -pub fn pop(&mut self) -> T -``` - -Pops the element at the end of the vector. This will decrease the length -of the vector by one. - -Panics if the vector is empty. - -Example: - -```rust title="bounded-vec-pop-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.push(1); - v.push(2); - - let two = v.pop(); - let one = v.pop(); - - assert(two == 2); - assert(one == 1); - // error: cannot pop from an empty vector - // let _ = v.pop(); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L108-L120 - - -### len - -```rust -pub fn len(self) -> u64 { -``` - -Returns the current length of this vector - -Example: - -```rust title="bounded-vec-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - assert(v.len() == 0); - - v.push(100); - assert(v.len() == 1); - - v.push(200); - v.push(300); - v.push(400); - assert(v.len() == 4); - - let _ = v.pop(); - let _ = v.pop(); - assert(v.len() == 2); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L125-L140 - - -### max_len - -```rust -pub fn max_len(_self: BoundedVec) -> u64 { -``` - -Returns the maximum length of this vector. This is always -equal to the `MaxLen` parameter this vector was initialized with. - -Example: - -```rust title="bounded-vec-max-len-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.max_len() == 5); - v.push(10); - assert(v.max_len() == 5); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L145-L151 - - -### storage - -```rust -pub fn storage(self) -> [T; MaxLen] { -``` - -Returns the internal array within this vector. -Since arrays in Noir are immutable, mutating the returned storage array will not mutate -the storage held internally by this vector. - -Note that uninitialized elements may be zeroed out! - -Example: - -```rust title="bounded-vec-storage-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - - assert(v.storage() == [0, 0, 0, 0, 0]); - - v.push(57); - assert(v.storage() == [57, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L156-L163 - - -### extend_from_array - -```rust -pub fn extend_from_array(&mut self, array: [T; Len]) -``` - -Pushes each element from the given array to this vector. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-array-example" showLineNumbers -let mut vec: BoundedVec = BoundedVec::new(); - vec.extend_from_array([2, 4]); - - assert(vec.len == 2); - assert(vec.get(0) == 2); - assert(vec.get(1) == 4); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L168-L175 - - -### extend_from_bounded_vec - -```rust -pub fn extend_from_bounded_vec(&mut self, vec: BoundedVec) -``` - -Pushes each element from the other vector to this vector. The length of -the other vector is left unchanged. - -Panics if pushing each element would cause the length of this vector -to exceed the maximum length. - -Example: - -```rust title="bounded-vec-extend-from-bounded-vec-example" showLineNumbers -let mut v1: BoundedVec = BoundedVec::new(); - let mut v2: BoundedVec = BoundedVec::new(); - - v2.extend_from_array([1, 2, 3]); - v1.extend_from_bounded_vec(v2); - - assert(v1.storage() == [1, 2, 3, 0, 0]); - assert(v2.storage() == [1, 2, 3, 0, 0, 0, 0]); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L180-L189 - - -### from_array - -```rust -pub fn from_array(array: [T; Len]) -> Self -``` - -Creates a new vector, populating it with values derived from an array input. -The maximum length of the vector is determined based on the type signature. - -Example: -```rust -let bounded_vec: BoundedVec = BoundedVec::from_array([1, 2, 3]) -``` - -### map - -```rust -pub fn map(self, f: fn[Env](T) -> U) -> BoundedVec -``` - -Creates a new vector of equal size by calling a closure on each element in this vector. - -Example: - -```rust title="bounded-vec-map-example" showLineNumbers -let vec: BoundedVec = BoundedVec::from_array([1, 2, 3, 4]); - let result = vec.map(|value| value * 2); -``` -> Source code: noir_stdlib/src/collections/bounded_vec.nr#L214-L217 - - -### any - -```rust -pub fn any(self, predicate: fn[Env](T) -> bool) -> bool -``` - -Returns true if the given predicate returns true for any element -in this vector. - -Example: - -```rust title="bounded-vec-any-example" showLineNumbers -let mut v: BoundedVec = BoundedVec::new(); - v.extend_from_array([2, 4, 6]); - - let all_even = !v.any(|elem: u32| elem % 2 != 0); - assert(all_even); -``` -> Source code: test_programs/noir_test_success/bounded_vec/src/main.nr#L256-L262 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/hashmap.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/hashmap.md deleted file mode 100644 index 408b6ba9da7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/hashmap.md +++ /dev/null @@ -1,570 +0,0 @@ ---- -title: HashMap -keywords: [noir, map, hash, hashmap] -sidebar_position: 1 ---- - -`HashMap` is used to efficiently store and look up key-value pairs. - -`HashMap` is a bounded type which can store anywhere from zero to `MaxLen` total elements. -Note that due to hash collisions, the actual maximum number of elements stored by any particular -hashmap is likely lower than `MaxLen`. This is true even with cryptographic hash functions since -every hash value will be performed modulo `MaxLen`. - -When creating `HashMap`s, the `MaxLen` generic should always be specified if it is not already -known. Otherwise, the compiler may infer a different value for `MaxLen` (such as zero), which -will likely change the result of the program. This behavior is set to become an error in future -versions instead. - -Example: - -```rust -// Create a mapping from Fields to u32s with a maximum length of 12 -// using a poseidon2 hasher -use std::hash::poseidon2::Poseidon2Hasher; -let mut map: HashMap> = HashMap::default(); - -map.insert(1, 2); -map.insert(3, 4); - -let two = map.get(1).unwrap(); -``` - -## Methods - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Creates a fresh, empty HashMap. - -When using this function, always make sure to specify the maximum size of the hash map. - -This is the same `default` from the `Default` implementation given further below. It is -repeated here for convenience since it is the recommended way to create a hashmap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -Because `HashMap` has so many generic arguments that are likely to be the same throughout -your program, it may be helpful to create a type alias: - -```rust title="type_alias" showLineNumbers -type MyMap = HashMap>; -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L196-L198 - - -### with_hasher - -```rust title="with_hasher" showLineNumbers -pub fn with_hasher(_build_hasher: B) -> Self - where - B: BuildHasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L82-L86 - - -Creates a hashmap with an existing `BuildHasher`. This can be used to ensure multiple -hashmaps are created with the same hasher instance. - -Example: - -```rust title="with_hasher_example" showLineNumbers -let my_hasher: BuildHasherDefault = Default::default(); - let hashmap: HashMap> = HashMap::with_hasher(my_hasher); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L207-L211 - - -### get - -```rust title="get" showLineNumbers -pub fn get( - self, - key: K - ) -> Option - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L278-L287 - - -Retrieves a value from the hashmap, returning `Option::none()` if it was not found. - -Example: - -```rust title="get_example" showLineNumbers -fn get_example(map: HashMap>) { - let x = map.get(12); - - if x.is_some() { - assert(x.unwrap() == 42); - } -} -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L299-L307 - - -### insert - -```rust title="insert" showLineNumbers -pub fn insert( - &mut self, - key: K, - value: V - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L313-L323 - - -Inserts a new key-value pair into the map. If the key was already in the map, its -previous value will be overridden with the newly provided one. - -Example: - -```rust title="insert_example" showLineNumbers -let mut map: HashMap> = HashMap::default(); - map.insert(12, 42); - assert(map.len() == 1); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L213-L217 - - -### remove - -```rust title="remove" showLineNumbers -pub fn remove( - &mut self, - key: K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L356-L365 - - -Removes the given key-value pair from the map. If the key was not already present -in the map, this does nothing. - -Example: - -```rust title="remove_example" showLineNumbers -map.remove(12); - assert(map.is_empty()); - - // If a key was not present in the map, remove does nothing - map.remove(12); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L221-L228 - - -### is_empty - -```rust title="is_empty" showLineNumbers -pub fn is_empty(self) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L115-L117 - - -True if the length of the hash map is empty. - -Example: - -```rust title="is_empty_example" showLineNumbers -assert(map.is_empty()); - - map.insert(1, 2); - assert(!map.is_empty()); - - map.remove(1); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L230-L238 - - -### len - -```rust title="len" showLineNumbers -pub fn len(self) -> u32 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L264-L266 - - -Returns the current length of this hash map. - -Example: - -```rust title="len_example" showLineNumbers -// This is equivalent to checking map.is_empty() - assert(map.len() == 0); - - map.insert(1, 2); - map.insert(3, 4); - map.insert(5, 6); - assert(map.len() == 3); - - // 3 was already present as a key in the hash map, so the length is unchanged - map.insert(3, 7); - assert(map.len() == 3); - - map.remove(1); - assert(map.len() == 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L240-L255 - - -### capacity - -```rust title="capacity" showLineNumbers -pub fn capacity(_self: Self) -> u32 { -``` -> Source code: noir_stdlib/src/collections/map.nr#L271-L273 - - -Returns the maximum capacity of this hashmap. This is always equal to the capacity -specified in the hashmap's type. - -Unlike hashmaps in general purpose programming languages, hashmaps in Noir have a -static capacity that does not increase as the map grows larger. Thus, this capacity -is also the maximum possible element count that can be inserted into the hashmap. -Due to hash collisions (modulo the hashmap length), it is likely the actual maximum -element count will be lower than the full capacity. - -Example: - -```rust title="capacity_example" showLineNumbers -let empty_map: HashMap> = HashMap::default(); - assert(empty_map.len() == 0); - assert(empty_map.capacity() == 42); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L257-L261 - - -### clear - -```rust title="clear" showLineNumbers -pub fn clear(&mut self) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L93-L95 - - -Clears the hashmap, removing all key-value pairs from it. - -Example: - -```rust title="clear_example" showLineNumbers -assert(!map.is_empty()); - map.clear(); - assert(map.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L263-L267 - - -### contains_key - -```rust title="contains_key" showLineNumbers -pub fn contains_key( - self, - key: K - ) -> bool - where - K: Hash + Eq, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L101-L110 - - -True if the hashmap contains the given key. Unlike `get`, this will not also return -the value associated with the key. - -Example: - -```rust title="contains_key_example" showLineNumbers -if map.contains_key(7) { - let value = map.get(7); - assert(value.is_some()); - } else { - println("No value for key 7!"); - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L269-L276 - - -### entries - -```rust title="entries" showLineNumbers -pub fn entries(self) -> BoundedVec<(K, V), N> { -``` -> Source code: noir_stdlib/src/collections/map.nr#L123-L125 - - -Returns a vector of each key-value pair present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="entries_example" showLineNumbers -let entries = map.entries(); - - // The length of a hashmap may not be compile-time known, so we - // need to loop over its capacity instead - for i in 0..map.capacity() { - if i < entries.len() { - let (key, value) = entries.get(i); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L310-L321 - - -### keys - -```rust title="keys" showLineNumbers -pub fn keys(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L144-L146 - - -Returns a vector of each key present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="keys_example" showLineNumbers -let keys = map.keys(); - - for i in 0..keys.max_len() { - if i < keys.len() { - let key = keys.get_unchecked(i); - let value = map.get(key).unwrap_unchecked(); - println(f"{key} -> {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L323-L333 - - -### values - -```rust title="values" showLineNumbers -pub fn values(self) -> BoundedVec { -``` -> Source code: noir_stdlib/src/collections/map.nr#L164-L166 - - -Returns a vector of each value present in the hashmap. - -The length of the returned vector is always equal to the length of the hashmap. - -Example: - -```rust title="values_example" showLineNumbers -let values = map.values(); - - for i in 0..values.max_len() { - if i < values.len() { - let value = values.get_unchecked(i); - println(f"Found value {value}"); - } - } -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L335-L344 - - -### iter_mut - -```rust title="iter_mut" showLineNumbers -pub fn iter_mut( - &mut self, - f: fn(K, V) -> (K, V) - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L183-L192 - - -Iterates through each key-value pair of the HashMap, setting each key-value pair to the -result returned from the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If this is not desired, use `iter_values_mut` if only values need to be mutated, -or `entries` if neither keys nor values need to be mutated. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_mut_example" showLineNumbers -// Add 1 to each key in the map, and double the value associated with that key. - map.iter_mut(|k, v| (k + 1, v * 2)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L348-L351 - - -### iter_keys_mut - -```rust title="iter_keys_mut" showLineNumbers -pub fn iter_keys_mut( - &mut self, - f: fn(K) -> K - ) - where - K: Eq + Hash, - B: BuildHasher, - H: Hasher { -``` -> Source code: noir_stdlib/src/collections/map.nr#L208-L217 - - -Iterates through the HashMap, mutating each key to the result returned from -the given function. - -Note that since keys can be mutated, the HashMap needs to be rebuilt as it is iterated -through. If only iteration is desired and the keys are not intended to be mutated, -prefer using `entries` instead. - -The iteration order is left unspecified. As a result, if two keys are mutated to become -equal, which of the two values that will be present for the key in the resulting map is also unspecified. - -Example: - -```rust title="iter_keys_mut_example" showLineNumbers -// Double each key, leaving the value associated with that key untouched - map.iter_keys_mut(|k| k * 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L353-L356 - - -### iter_values_mut - -```rust title="iter_values_mut" showLineNumbers -pub fn iter_values_mut(&mut self, f: fn(V) -> V) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L233-L235 - - -Iterates through the HashMap, applying the given function to each value and mutating the -value to equal the result. This function is more efficient than `iter_mut` and `iter_keys_mut` -because the keys are untouched and the underlying hashmap thus does not need to be reordered. - -Example: - -```rust title="iter_values_mut_example" showLineNumbers -// Halve each value - map.iter_values_mut(|v| v / 2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L358-L361 - - -### retain - -```rust title="retain" showLineNumbers -pub fn retain(&mut self, f: fn(K, V) -> bool) { -``` -> Source code: noir_stdlib/src/collections/map.nr#L247-L249 - - -Retains only the key-value pairs for which the given function returns true. -Any key-value pairs for which the function returns false will be removed from the map. - -Example: - -```rust title="retain_example" showLineNumbers -map.retain(|k, v| (k != 0) & (v != 0)); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L281-L283 - - -## Trait Implementations - -### default - -```rust title="default" showLineNumbers -impl Default for HashMap -where - B: BuildHasher + Default, - H: Hasher + Default -{ - fn default() -> Self { -``` -> Source code: noir_stdlib/src/collections/map.nr#L462-L469 - - -Constructs an empty HashMap. - -Example: - -```rust title="default_example" showLineNumbers -let hashmap: HashMap> = HashMap::default(); - assert(hashmap.is_empty()); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L202-L205 - - -### eq - -```rust title="eq" showLineNumbers -impl Eq for HashMap -where - K: Eq + Hash, - V: Eq, - B: BuildHasher, - H: Hasher -{ - fn eq(self, other: HashMap) -> bool { -``` -> Source code: noir_stdlib/src/collections/map.nr#L426-L435 - - -Checks if two HashMaps are equal. - -Example: - -```rust title="eq_example" showLineNumbers -let mut map1: HashMap> = HashMap::default(); - let mut map2: HashMap> = HashMap::default(); - - map1.insert(1, 2); - map1.insert(3, 4); - - map2.insert(3, 4); - map2.insert(1, 2); - - assert(map1 == map2); -``` -> Source code: test_programs/execution_success/hashmap/src/main.nr#L285-L296 - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/index.md deleted file mode 100644 index ea84c6d5c21..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/index.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: Containers -description: Container types provided by Noir's standard library for storing and retrieving data -keywords: [containers, data types, vec, hashmap] ---- diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/vec.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/vec.mdx deleted file mode 100644 index 475011922f8..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/containers/vec.mdx +++ /dev/null @@ -1,170 +0,0 @@ ---- -title: Vectors -description: Delve into the Vec data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. -keywords: [noir, vector type, methods, examples, dynamic arrays] -sidebar_position: 6 ---- - -import Experimental from '@site/src/components/Notes/_experimental.mdx'; - - - -A vector is a collection type similar to Rust's `Vec` type. In Noir, it is a convenient way to use slices as mutable arrays. - -Example: - -```rust -let mut vector: Vec = Vec::new(); -for i in 0..5 { - vector.push(i); -} -assert(vector.len() == 5); -``` - -## Methods - -### new - -Creates a new, empty vector. - -```rust -pub fn new() -> Self -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### from_slice - -Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. - -```rust -pub fn from_slice(slice: [T]) -> Self -``` - -Example: - -```rust -let slice: [Field] = &[1, 2, 3]; -let vector_from_slice = Vec::from_slice(slice); -assert(vector_from_slice.len() == 3); -``` - -### len - -Returns the number of elements in the vector. - -```rust -pub fn len(self) -> Field -``` - -Example: - -```rust -let empty_vector: Vec = Vec::new(); -assert(empty_vector.len() == 0); -``` - -### get - -Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. - -```rust -pub fn get(self, index: Field) -> T -``` - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -``` - -### set - -```rust -pub fn set(&mut self: Self, index: u64, value: T) { -``` - -Writes an element to the vector at the given index, starting from zero. - -Panics if the index points beyond the vector's end. - -Example: - -```rust -let vector: Vec = Vec::from_slice(&[10, 20, 30]); -assert(vector.get(1) == 20); -vector.set(1, 42); -assert(vector.get(1) == 42); -``` - -### push - -Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. - -```rust -pub fn push(&mut self, elem: T) -``` - -Example: - -```rust -let mut vector: Vec = Vec::new(); -vector.push(10); -assert(vector.len() == 1); -``` - -### pop - -Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. - -```rust -pub fn pop(&mut self) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20]); -let popped_elem = vector.pop(); -assert(popped_elem == 20); -assert(vector.len() == 1); -``` - -### insert - -Inserts an element at a specified index, shifting subsequent elements to the right. - -```rust -pub fn insert(&mut self, index: Field, elem: T) -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 30]); -vector.insert(1, 20); -assert(vector.get(1) == 20); -``` - -### remove - -Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. - -```rust -pub fn remove(&mut self, index: Field) -> T -``` - -Example: - -```rust -let mut vector = Vec::from_slice(&[10, 20, 30]); -let removed_elem = vector.remove(1); -assert(removed_elem == 20); -assert(vector.len() == 2); -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/_category_.json deleted file mode 100644 index 5d694210bbf..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 0, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ciphers.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ciphers.mdx deleted file mode 100644 index e83e26efb97..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ciphers.mdx +++ /dev/null @@ -1,32 +0,0 @@ ---- -title: Ciphers -description: - Learn about the implemented ciphers ready to use for any Noir project -keywords: - [ciphers, Noir project, aes128, encrypt] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## aes128 - -Given a plaintext as an array of bytes, returns the corresponding aes128 ciphertext (CBC mode). Input padding is automatically performed using PKCS#7, so that the output length is `input.len() + (16 - input.len() % 16)`. - -```rust title="aes128" showLineNumbers -pub fn aes128_encrypt(input: [u8; N], iv: [u8; 16], key: [u8; 16]) -> [u8] {} -``` -> Source code: noir_stdlib/src/aes128.nr#L2-L4 - - -```rust -fn main() { - let input: [u8; 4] = [0, 12, 3, 15] // Random bytes, will be padded to 16 bytes. - let iv: [u8; 16] = [0; 16]; // Initialisation vector - let key: [u8; 16] = [0; 16] // AES key - let ciphertext = std::aes128::aes128_encrypt(inputs.as_bytes(), iv.as_bytes(), key.as_bytes()); // In this case, the output length will be 16 bytes. -} -``` - - - \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ec_primitives.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ec_primitives.md deleted file mode 100644 index f839b4a228e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ec_primitives.md +++ /dev/null @@ -1,102 +0,0 @@ ---- -title: Elliptic Curve Primitives -keywords: [cryptographic primitives, Noir project] -sidebar_position: 4 ---- - -Data structures and methods on them that allow you to carry out computations involving elliptic -curves over the (mathematical) field corresponding to `Field`. For the field currently at our -disposal, applications would involve a curve embedded in BN254, e.g. the -[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). - -## Data structures - -### Elliptic curve configurations - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic -curve you want to use, which would be specified using any one of the methods -`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the -defining equation together with a generator point as parameters. You can find more detail in the -comments in -[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/master/noir_stdlib/src/ec.nr), but -the gist of it is that the elliptic curves of interest are usually expressed in one of the standard -forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, -you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly -together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates -requiring more coordinates but allowing for more efficient implementations of elliptic curve -operations). Conversions between all of these forms are provided, and under the hood these -conversions are done whenever an operation is more efficient in a different representation (or a -mixed coordinate representation is employed). - -### Points - -(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the -elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` -does indeed lie on `c` by calling `c.contains(p1)`. - -## Methods - -(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use -`std::ec::tecurve::affine::Point`) - -- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is - zero by calling `p.is_zero()`. -- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling - `p1.eq(p2)`. -- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two - points is accomplished by calling `c.add(p1,p2)`. -- **Negation**: For a point `p: Point`, `p.negate()` is its negation. -- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by - calling `c.subtract(p1,p2)`. -- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, - scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit - array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` -- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, - multi-scalar multiplication is given by `c.msm(n,p)`. -- **Coordinate representation conversions**: The `into_group` method converts a point or curve - configuration in the affine representation to one in the CurveGroup representation, and - `into_affine` goes in the other direction. -- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent - and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their - configurations or points. `swcurve` is more general and a curve c of one of the other two types - may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying - on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling - `c.map_into_swcurve(p)`. -- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a - `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of - the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where - `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to - satisfy are specified in the comments - [here](https://github.com/noir-lang/noir/blob/master/noir_stdlib/src/ec.nr)). - -## Examples - -The -[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/test_programs/compile_success_empty/ec_baby_jubjub/src/main.nr) -illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more -interesting examples in Noir would be: - -Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key -from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, -for example, this code would do: - -```rust -use std::ec::tecurve::affine::{Curve, Point}; - -fn bjj_pub_key(priv_key: Field) -> Point -{ - - let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); - - let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); - - bjj.mul(priv_key,base_pt) -} -``` - -This would come in handy in a Merkle proof. - -- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash - function. See - [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for - the case of Baby Jubjub and the Poseidon hash function. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx deleted file mode 100644 index 4394b48f907..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/ecdsa_sig_verification.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: ECDSA Signature Verification -description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves -keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] -sidebar_position: 3 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. - -## ecdsa_secp256k1::verify_signature - -Verifier for ECDSA Secp256k1 signatures. -See ecdsa_secp256k1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256k1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256k1::verify_signature_slice - -Verifier for ECDSA Secp256k1 signatures where the message is a slice. - -```rust title="ecdsa_secp256k1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256k1.nr#L13-L20 - - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures. -See ecdsa_secp256r1::verify_signature_slice for a version that accepts slices directly. - -```rust title="ecdsa_secp256r1" showLineNumbers -pub fn verify_signature( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L2-L9 - - -example: - -```rust -fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { - let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); -} -``` - - - -## ecdsa_secp256r1::verify_signature - -Verifier for ECDSA Secp256r1 signatures where the message is a slice. - -```rust title="ecdsa_secp256r1_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: [u8; 32], - public_key_y: [u8; 32], - signature: [u8; 64], - message_hash: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/ecdsa_secp256r1.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/eddsa.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/eddsa.mdx deleted file mode 100644 index 1ad42a5ac96..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/eddsa.mdx +++ /dev/null @@ -1,37 +0,0 @@ ---- -title: EdDSA Verification -description: Learn about the cryptographic primitives regarding EdDSA -keywords: [cryptographic primitives, Noir project, eddsa, signatures] -sidebar_position: 5 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## eddsa::eddsa_poseidon_verify - -Verifier for EdDSA signatures - -```rust -fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool -``` - -It is also possible to specify the hash algorithm used for the signature by using the `eddsa_verify` function by passing a type implementing the Hasher trait with the turbofish operator. -For instance, if you want to use Poseidon2 instead, you can do the following: -```rust -use std::hash::poseidon2::Poseidon2Hasher; - -eddsa_verify::(pub_key_a.x, pub_key_a.y, s_a, r8_a.x, r8_a.y, msg); -``` - - - -## eddsa::eddsa_to_pub - -Private to public key conversion. - -Returns `(pub_key_x, pub_key_y)` - -```rust -fn eddsa_to_pub(secret : Field) -> (Field, Field) -``` - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx deleted file mode 100644 index 14d7dda7f0d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/embedded_curve_ops.mdx +++ /dev/null @@ -1,98 +0,0 @@ ---- -title: Scalar multiplication -description: See how you can perform scalar multiplication in Noir -keywords: [cryptographic primitives, Noir project, scalar multiplication] -sidebar_position: 1 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -The following functions perform operations over the embedded curve whose coordinates are defined by the configured noir field. -For the BN254 scalar field, this is BabyJubJub or Grumpkin. - -:::note -Suffixes `_low` and `_high` denote low and high limbs of a scalar. -::: - -## embedded_curve_ops::multi_scalar_mul - -Performs multi scalar multiplication over the embedded curve. -The function accepts arbitrary amount of point-scalar pairs on the input, it multiplies the individual pairs over -the curve and returns a sum of the resulting points. - -Points represented as x and y coordinates [x1, y1, x2, y2, ...], scalars as low and high limbs [low1, high1, low2, high2, ...]. - -```rust title="multi_scalar_mul" showLineNumbers -pub fn multi_scalar_mul( - points: [EmbeddedCurvePoint; N], - scalars: [EmbeddedCurveScalar; N] -) -> [Field; 3] -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L62-L67 - - -example - -```rust -fn main(point_x: Field, point_y: Field, scalar_low: Field, scalar_high: Field) { - let point = std::embedded_curve_ops::multi_scalar_mul([point_x, point_y], [scalar_low, scalar_high]); - println(point); -} -``` - -## embedded_curve_ops::fixed_base_scalar_mul - -Performs fixed base scalar multiplication over the embedded curve (multiplies input scalar with a generator point). -The function accepts a single scalar on the input represented as 2 fields. - -```rust title="fixed_base_scalar_mul" showLineNumbers -pub fn fixed_base_scalar_mul( - scalar_low: Field, - scalar_high: Field -) -> [Field; 3] -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L70-L75 - - -example - -```rust -fn main(scalar_low: Field, scalar_high: Field) { - let point = std::embedded_curve_ops::fixed_base_scalar_mul(scalar_low, scalar_high); - println(point); -} -``` - -## embedded_curve_ops::embedded_curve_add - -Adds two points on the embedded curve. -This function takes two `EmbeddedCurvePoint` structures as parameters, representing points on the curve, and returns a new `EmbeddedCurvePoint` structure that represents their sum. - -### Parameters: -- `point1` (`EmbeddedCurvePoint`): The first point to add. -- `point2` (`EmbeddedCurvePoint`): The second point to add. - -### Returns: -- `EmbeddedCurvePoint`: The resulting point after the addition of `point1` and `point2`. - -```rust title="embedded_curve_add" showLineNumbers -fn embedded_curve_add( - point1: EmbeddedCurvePoint, - point2: EmbeddedCurvePoint -) -> EmbeddedCurvePoint -``` -> Source code: noir_stdlib/src/embedded_curve_ops.nr#L84-L89 - - -example - -```rust -fn main() { - let point1 = EmbeddedCurvePoint { x: 1, y: 2 }; - let point2 = EmbeddedCurvePoint { x: 3, y: 4 }; - let result = std::embedded_curve_ops::embedded_curve_add(point1, point2); - println!("Resulting Point: ({}, {})", result.x, result.y); -} -``` - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/hashes.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/hashes.mdx deleted file mode 100644 index 18132b9a4dc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/hashes.mdx +++ /dev/null @@ -1,246 +0,0 @@ ---- -title: Hash methods -description: - Learn about the cryptographic primitives ready to use for any Noir project, including sha256, - blake2s, pedersen, mimc_bn254 and mimc -keywords: - [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] -sidebar_position: 0 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## sha256 - -Given an array of bytes, returns the resulting sha256 hash. -Specify a message_size to hash only the first `message_size` bytes of the input. - -```rust title="sha256" showLineNumbers -pub fn sha256(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L11-L13 - - -example: -```rust title="sha256_var" showLineNumbers -let digest = std::hash::sha256_var([x as u8], 1); -``` -> Source code: test_programs/execution_success/sha256/src/main.nr#L16-L18 - - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::sha256::sha256_var(x, 4); -} -``` - - - - -## blake2s - -Given an array of bytes, returns an array with the Blake2 hash - -```rust title="blake2s" showLineNumbers -pub fn blake2s(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L17-L19 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake2s(x); -} -``` - - - -## blake3 - -Given an array of bytes, returns an array with the Blake3 hash - -```rust title="blake3" showLineNumbers -pub fn blake3(input: [u8; N]) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L23-L25 - - -example: - -```rust -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::blake3(x); -} -``` - - - -## pedersen_hash - -Given an array of Fields, returns the Pedersen hash. - -```rust title="pedersen_hash" showLineNumbers -pub fn pedersen_hash(input: [Field; N]) -> Field -``` -> Source code: noir_stdlib/src/hash.nr#L42-L44 - - -example: - -```rust title="pedersen-hash" showLineNumbers -fn main(x: Field, y: Field, expected_hash: Field) { - let hash = std::hash::pedersen_hash([x, y]); - assert_eq(hash, expected_hash); -} -``` -> Source code: test_programs/execution_success/pedersen_hash/src/main.nr#L1-L7 - - - - -## pedersen_commitment - -Given an array of Fields, returns the Pedersen commitment. - -```rust title="pedersen_commitment" showLineNumbers -pub fn pedersen_commitment(input: [Field; N]) -> EmbeddedCurvePoint { -``` -> Source code: noir_stdlib/src/hash.nr#L28-L30 - - -example: - -```rust title="pedersen-commitment" showLineNumbers -fn main(x: Field, y: Field, expected_commitment: std::embedded_curve_ops::EmbeddedCurvePoint) { - let commitment = std::hash::pedersen_commitment([x, y]); - assert_eq(commitment.x, expected_commitment.x); - assert_eq(commitment.y, expected_commitment.y); -} -``` -> Source code: test_programs/execution_success/pedersen_commitment/src/main.nr#L1-L8 - - - - -## keccak256 - -Given an array of bytes (`u8`), returns the resulting keccak hash as an array of -32 bytes (`[u8; 32]`). Specify a message_size to hash only the first -`message_size` bytes of the input. - -```rust title="keccak256" showLineNumbers -pub fn keccak256(input: [u8; N], message_size: u32) -> [u8; 32] -``` -> Source code: noir_stdlib/src/hash.nr#L64-L66 - - -example: - -```rust title="keccak256" showLineNumbers -fn main(x: Field, result: [u8; 32]) { - // We use the `as` keyword here to denote the fact that we want to take just the first byte from the x Field - // The padding is taken care of by the program - let digest = std::hash::keccak256([x as u8], 1); - assert(digest == result); - - //#1399: variable message size - let message_size = 4; - let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); - let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); - - assert(hash_a == hash_b); - - let message_size_big = 8; - let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); - - assert(hash_a != hash_c); -} -``` -> Source code: test_programs/execution_success/keccak256/src/main.nr#L1-L21 - - - - -## poseidon - -Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify -how many inputs are there to your Poseidon function. - -```rust -// example for hash_1, hash_2 accepts an array of length 2, etc -fn hash_1(input: [Field; 1]) -> Field -``` - -example: - -```rust title="poseidon" showLineNumbers -use std::hash::poseidon; -use std::hash::poseidon2; - -fn main(x1: [Field; 2], y1: pub Field, x2: [Field; 4], y2: pub Field, x3: [Field; 4], y3: Field) { - let hash1 = poseidon::bn254::hash_2(x1); - assert(hash1 == y1); - - let hash2 = poseidon::bn254::hash_4(x2); - assert(hash2 == y2); - - let hash3 = poseidon2::Poseidon2::hash(x3, x3.len()); - assert(hash3 == y3); -} -``` -> Source code: test_programs/execution_success/poseidon_bn254_hash/src/main.nr#L1-L15 - - -## poseidon 2 - -Given an array of Fields, returns a new Field with the Poseidon2 Hash. Contrary to the Poseidon -function, there is only one hash and you can specify a message_size to hash only the first -`message_size` bytes of the input, - -```rust -// example for hashing the first three elements of the input -Poseidon2::hash(input, 3); -``` - -The above example for Poseidon also includes Poseidon2. - -## mimc_bn254 and mimc - -`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by -providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if -you're willing to input your own constants: - -```rust -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field -``` - -otherwise, use the `mimc_bn254` method: - -```rust -fn mimc_bn254(array: [Field; N]) -> Field -``` - -example: - -```rust - -fn main() { - let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc::mimc_bn254(x); -} -``` - -## hash_to_field - -```rust -fn hash_to_field(_input : [Field]) -> Field {} -``` - -Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return -a value which can be represented as a `Field`. - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/index.md deleted file mode 100644 index 650f30165d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/index.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -title: Cryptographic Primitives -description: - Learn about the cryptographic primitives ready to use for any Noir project -keywords: - [ - cryptographic primitives, - Noir project, - ] ---- - -The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. - -Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/schnorr.mdx b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/schnorr.mdx deleted file mode 100644 index b59e69c8f07..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/cryptographic_primitives/schnorr.mdx +++ /dev/null @@ -1,64 +0,0 @@ ---- -title: Schnorr Signatures -description: Learn how you can verify Schnorr signatures using Noir -keywords: [cryptographic primitives, Noir project, schnorr, signatures] -sidebar_position: 2 ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -## schnorr::verify_signature - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). -See schnorr::verify_signature_slice for a version that works directly on slices. - -```rust title="schnorr_verify" showLineNumbers -pub fn verify_signature( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8; N] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L2-L9 - - -where `_signature` can be generated like so using the npm package -[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) - -```js -const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); -const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); - -... - -const barretenberg = await BarretenbergWasm.new(); -const schnorr = new Schnorr(barretenberg); -const pubKey = schnorr.computePublicKey(privateKey); -const message = ... -const signature = Array.from( - schnorr.constructSignature(hash, privateKey).toBuffer() -); - -... -``` - - - -## schnorr::verify_signature_slice - -Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin) -where the message is a slice. - -```rust title="schnorr_verify_slice" showLineNumbers -pub fn verify_signature_slice( - public_key_x: Field, - public_key_y: Field, - signature: [u8; 64], - message: [u8] -) -> bool -``` -> Source code: noir_stdlib/src/schnorr.nr#L13-L20 - - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/is_unconstrained.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/is_unconstrained.md deleted file mode 100644 index bb157e719dc..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/is_unconstrained.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Is Unconstrained Function -description: - The is_unconstrained function returns wether the context at that point of the program is unconstrained or not. -keywords: - [ - unconstrained - ] ---- - -It's very common for functions in circuits to take unconstrained hints of an expensive computation and then verify it. This is done by running the hint in an unconstrained context and then verifying the result in a constrained context. - -When a function is marked as unconstrained, any subsequent functions that it calls will also be run in an unconstrained context. However, if we are implementing a library function, other users might call it within an unconstrained context or a constrained one. Generally, in an unconstrained context we prefer just computing the result instead of taking a hint of it and verifying it, since that'd mean doing the same computation twice: - -```rust - -fn my_expensive_computation(){ - ... -} - -unconstrained fn my_expensive_computation_hint(){ - my_expensive_computation() -} - -pub fn external_interface(){ - my_expensive_computation_hint(); - // verify my_expensive_computation: If external_interface is called from unconstrained, this is redundant - ... -} - -``` - -In order to improve the performance in an unconstrained context you can use the function at `std::runtime::is_unconstrained() -> bool`: - - -```rust -use dep::std::runtime::is_unconstrained; - -fn my_expensive_computation(){ - ... -} - -unconstrained fn my_expensive_computation_hint(){ - my_expensive_computation() -} - -pub fn external_interface(){ - if is_unconstrained() { - my_expensive_computation(); - } else { - my_expensive_computation_hint(); - // verify my_expensive_computation - ... - } -} - -``` - -The is_unconstrained result is resolved at compile time, so in unconstrained contexts the compiler removes the else branch, and in constrained contexts the compiler removes the if branch, reducing the amount of compute necessary to run external_interface. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/logging.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/logging.md deleted file mode 100644 index db75ef9f86f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/logging.md +++ /dev/null @@ -1,78 +0,0 @@ ---- -title: Logging -description: - Learn how to use the println statement for debugging in Noir with this tutorial. Understand the - basics of logging in Noir and how to implement it in your code. -keywords: - [ - noir logging, - println statement, - print statement, - debugging in noir, - noir std library, - logging tutorial, - basic logging in noir, - noir logging implementation, - noir debugging techniques, - rust, - ] ---- - -The standard library provides two familiar statements you can use: `println` and `print`. Despite being a limited implementation of rust's `println!` and `print!` macros, these constructs can be useful for debugging. - -You can print the output of both statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are print statements in your tests). - -It is recommended to use `nargo execute` if you want to debug failing constraints with `println` or `print` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). Neither `println`, nor `print` are callable for failed constraints caught at compile time. - -Both `print` and `println` are generic functions which can work on integers, fields, strings, and even structs or expressions. Note however, that slices are currently unsupported. For example: - -```rust -struct Person { - age: Field, - height: Field, -} - -fn main(age: Field, height: Field) { - let person = Person { - age: age, - height: height, - }; - println(person); - println(age + height); - println("Hello world!"); -} -``` - -You can print different types in the same statement (including strings) with a type called `fmtstr`. It can be specified in the same way as a normal string, just prepended with an "f" character: - -```rust - let fmt_str = f"i: {i}, j: {j}"; - println(fmt_str); - - let s = myStruct { y: x, x: y }; - println(s); - - println(f"i: {i}, s: {s}"); - - println(x); - println([x, y]); - - let foo = fooStruct { my_struct: s, foo: 15 }; - println(f"s: {s}, foo: {foo}"); - - println(15); // prints 0x0f, implicit Field - println(-1 as u8); // prints 255 - println(-1 as i8); // prints -1 -``` - -Examples shown above are interchangeable between the two `print` statements: - -```rust -let person = Person { age : age, height : height }; - -println(person); -print(person); - -println("Hello world!"); // Prints with a newline at the end of the input -print("Hello world!"); // Prints the input and keeps cursor on the same line -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/merkle_trees.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/merkle_trees.md deleted file mode 100644 index 6a9ebf72ada..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/merkle_trees.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -title: Merkle Trees -description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. -keywords: - [ - Merkle trees in Noir, - Noir programming language, - check membership, - computing root from leaf, - Noir Merkle tree implementation, - Merkle tree tutorial, - Merkle tree code examples, - Noir libraries, - pedersen hash., - ] ---- - -## compute_merkle_root - -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](./cryptographic_primitives/hashes.mdx#pedersen_hash). - -```rust -fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field -``` - -example: - -```rust -/** - // these values are for this example only - index = "0" - priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" - secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" - note_hash_path = [ - "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", - "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", - "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" - ] - */ -fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { - - let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); - let pubkey_x = pubkey[0]; - let pubkey_y = pubkey[1]; - let note_commitment = std::hash::pedersen(&[pubkey_x, pubkey_y, secret]); - - let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path.as_slice()); - println(root); -} -``` - -To check merkle tree membership: - -1. Include a merkle root as a program input. -2. Compute the merkle root of a given leaf, index and hash path. -3. Assert the merkle roots are equal. - -For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/options.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/options.md deleted file mode 100644 index a1bd4e1de5f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/options.md +++ /dev/null @@ -1,101 +0,0 @@ ---- -title: Option Type ---- - -The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. - -```rust -struct Option { - None, - Some(T), -} -``` - -The `Option` type, already imported into your Noir program, can be used directly: - -```rust -fn main() { - let none = Option::none(); - let some = Option::some(3); -} -``` - -See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. - -## Methods - -### none - -Constructs a none value. - -### some - -Constructs a some wrapper around a given value. - -### is_none - -Returns true if the Option is None. - -### is_some - -Returns true of the Option is Some. - -### unwrap - -Asserts `self.is_some()` and returns the wrapped value. - -### unwrap_unchecked - -Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. - -### unwrap_or - -Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. - -### unwrap_or_else - -Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. - -### expect - -Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value. The custom message is expected to be a format string. - -### map - -If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. - -### map_or - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. - -### map_or_else - -If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. - -### and - -Returns None if self is None. Otherwise, this returns `other`. - -### and_then - -If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. - -### or - -If self is Some, return self. Otherwise, return `other`. - -### or_else - -If self is Some, return self. Otherwise, return `default()`. - -### xor - -If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. - -### filter - -Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. - -### flatten - -Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/recursion.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/recursion.md deleted file mode 100644 index 8cfb37fc52d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/recursion.md +++ /dev/null @@ -1,85 +0,0 @@ ---- -title: Recursive Proofs -description: Learn about how to write recursive proofs in Noir. -keywords: [recursion, recursive proofs, verification_key, verify_proof] ---- - -import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; - -Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. - -Read [the explainer on recursion](../../explainers/explainer-recursion.md) to know more about this function and the [guide on how to use it.](../../how_to/how-to-recursion.md) - -## The `#[recursive]` Attribute - -In Noir, the `#[recursive]` attribute is used to indicate that a circuit is designed for recursive proof generation. When applied, it informs the compiler and the tooling that the circuit should be compiled in a way that makes its proofs suitable for recursive verification. This attribute eliminates the need for manual flagging of recursion at the tooling level, streamlining the proof generation process for recursive circuits. - -### Example usage with `#[recursive]` - -```rust -#[recursive] -fn main(x: Field, y: pub Field) { - assert(x == y, "x and y are not equal"); -} - -// This marks the circuit as recursion-friendly and indicates that proofs generated from this circuit -// are intended for recursive verification. -``` - -By incorporating this attribute directly in the circuit's definition, tooling like Nargo and NoirJS can automatically execute recursive-specific duties for Noir programs (e.g. recursive-friendly proof artifact generation) without additional flags or configurations. - -## Verifying Recursive Proofs - -```rust -#[foreign(recursive_aggregation)] -pub fn verify_proof(verification_key: [Field], proof: [Field], public_inputs: [Field], key_hash: Field) {} -``` - - - -## Example usage - -```rust - -fn main( - verification_key : [Field; 114], - proof : [Field; 93], - public_inputs : [Field; 1], - key_hash : Field, - proof_b : [Field; 93], -) { - std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash - ); - - std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash - ); -} -``` - -You can see a full example of recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). - -## Parameters - -### `verification_key` - -The verification key for the zk program that is being verified. - -### `proof` - -The proof for the zk program that is being verified. - -### `public_inputs` - -These represent the public inputs of the proof we are verifying. - -### `key_hash` - -A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/traits.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/traits.md deleted file mode 100644 index a14312d2792..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/traits.md +++ /dev/null @@ -1,464 +0,0 @@ ---- -title: Traits -description: Noir's stdlib provides a few commonly used traits. -keywords: [traits, trait, interface, protocol, default, add, eq] ---- - -## `std::default` - -### `std::default::Default` - -```rust title="default-trait" showLineNumbers -trait Default { - fn default() -> Self; -} -``` -> Source code: noir_stdlib/src/default.nr#L1-L5 - - -Constructs a default value of a type. - -Implementations: -```rust -impl Default for Field { .. } - -impl Default for i8 { .. } -impl Default for i16 { .. } -impl Default for i32 { .. } -impl Default for i64 { .. } - -impl Default for u8 { .. } -impl Default for u16 { .. } -impl Default for u32 { .. } -impl Default for u64 { .. } - -impl Default for () { .. } -impl Default for bool { .. } - -impl Default for [T; N] - where T: Default { .. } - -impl Default for [T] { .. } - -impl Default for (A, B) - where A: Default, B: Default { .. } - -impl Default for (A, B, C) - where A: Default, B: Default, C: Default { .. } - -impl Default for (A, B, C, D) - where A: Default, B: Default, C: Default, D: Default { .. } - -impl Default for (A, B, C, D, E) - where A: Default, B: Default, C: Default, D: Default, E: Default { .. } -``` - -For primitive integer types, the return value of `default` is `0`. Container -types such as arrays are filled with default values of their element type, -except slices whose length is unknown and thus defaulted to zero. - - -## `std::convert` - -### `std::convert::From` - -```rust title="from-trait" showLineNumbers -trait From { - fn from(input: T) -> Self; -} -``` -> Source code: noir_stdlib/src/convert.nr#L1-L5 - - -The `From` trait defines how to convert from a given type `T` to the type on which the trait is implemented. - -The Noir standard library provides a number of implementations of `From` between primitive types. -```rust title="from-impls" showLineNumbers -// Unsigned integers - -impl From for u32 { fn from(value: u8) -> u32 { value as u32 } } - -impl From for u64 { fn from(value: u8) -> u64 { value as u64 } } -impl From for u64 { fn from(value: u32) -> u64 { value as u64 } } - -impl From for Field { fn from(value: u8) -> Field { value as Field } } -impl From for Field { fn from(value: u32) -> Field { value as Field } } -impl From for Field { fn from(value: u64) -> Field { value as Field } } - -// Signed integers - -impl From for i32 { fn from(value: i8) -> i32 { value as i32 } } - -impl From for i64 { fn from(value: i8) -> i64 { value as i64 } } -impl From for i64 { fn from(value: i32) -> i64 { value as i64 } } - -// Booleans -impl From for u8 { fn from(value: bool) -> u8 { value as u8 } } -impl From for u32 { fn from(value: bool) -> u32 { value as u32 } } -impl From for u64 { fn from(value: bool) -> u64 { value as u64 } } -impl From for i8 { fn from(value: bool) -> i8 { value as i8 } } -impl From for i32 { fn from(value: bool) -> i32 { value as i32 } } -impl From for i64 { fn from(value: bool) -> i64 { value as i64 } } -impl From for Field { fn from(value: bool) -> Field { value as Field } } -``` -> Source code: noir_stdlib/src/convert.nr#L25-L52 - - -#### When to implement `From` - -As a general rule of thumb, `From` may be implemented in the [situations where it would be suitable in Rust](https://doc.rust-lang.org/std/convert/trait.From.html#when-to-implement-from): - -- The conversion is *infallible*: Noir does not provide an equivalent to Rust's `TryFrom`, if the conversion can fail then provide a named method instead. -- The conversion is *lossless*: semantically, it should not lose or discard information. For example, `u32: From` can losslessly convert any `u16` into a valid `u32` such that the original `u16` can be recovered. On the other hand, `u16: From` should not be implemented as `2**16` is a `u32` which cannot be losslessly converted into a `u16`. -- The conversion is *value-preserving*: the conceptual kind and meaning of the resulting value is the same, even though the Noir type and technical representation might be different. While it's possible to infallibly and losslessly convert a `u8` into a `str<2>` hex representation, `4u8` and `"04"` are too different for `str<2>: From` to be implemented. -- The conversion is *obvious*: it's the only reasonable conversion between the two types. If there's ambiguity on how to convert between them such that the same input could potentially map to two different values then a named method should be used. For instance rather than implementing `U128: From<[u8; 16]>`, the methods `U128::from_le_bytes` and `U128::from_be_bytes` are used as otherwise the endianness of the array would be ambiguous, resulting in two potential values of `U128` from the same byte array. - -One additional recommendation specific to Noir is: -- The conversion is *efficient*: it's relatively cheap to convert between the two types. Due to being a ZK DSL, it's more important to avoid unnecessary computation compared to Rust. If the implementation of `From` would encourage users to perform unnecessary conversion, resulting in additional proving time, then it may be preferable to expose functionality such that this conversion may be avoided. - -### `std::convert::Into` - -The `Into` trait is defined as the reciprocal of `From`. It should be easy to convince yourself that if we can convert to type `A` from type `B`, then it's possible to convert type `B` into type `A`. - -For this reason, implementing `From` on a type will automatically generate a matching `Into` implementation. One should always prefer implementing `From` over `Into` as implementing `Into` will not generate a matching `From` implementation. - -```rust title="into-trait" showLineNumbers -trait Into { - fn into(self) -> T; -} - -impl Into for U where T: From { - fn into(self) -> T { - T::from(self) - } -} -``` -> Source code: noir_stdlib/src/convert.nr#L13-L23 - - -`Into` is most useful when passing function arguments where the types don't quite match up with what the function expects. In this case, the compiler has enough type information to perform the necessary conversion by just appending `.into()` onto the arguments in question. - - -## `std::cmp` - -### `std::cmp::Eq` - -```rust title="eq-trait" showLineNumbers -trait Eq { - fn eq(self, other: Self) -> bool; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L1-L5 - - -Returns `true` if `self` is equal to `other`. Implementing this trait on a type -allows the type to be used with `==` and `!=`. - -Implementations: -```rust -impl Eq for Field { .. } - -impl Eq for i8 { .. } -impl Eq for i16 { .. } -impl Eq for i32 { .. } -impl Eq for i64 { .. } - -impl Eq for u8 { .. } -impl Eq for u16 { .. } -impl Eq for u32 { .. } -impl Eq for u64 { .. } - -impl Eq for () { .. } -impl Eq for bool { .. } - -impl Eq for [T; N] - where T: Eq { .. } - -impl Eq for [T] - where T: Eq { .. } - -impl Eq for (A, B) - where A: Eq, B: Eq { .. } - -impl Eq for (A, B, C) - where A: Eq, B: Eq, C: Eq { .. } - -impl Eq for (A, B, C, D) - where A: Eq, B: Eq, C: Eq, D: Eq { .. } - -impl Eq for (A, B, C, D, E) - where A: Eq, B: Eq, C: Eq, D: Eq, E: Eq { .. } -``` - -### `std::cmp::Ord` - -```rust title="ord-trait" showLineNumbers -trait Ord { - fn cmp(self, other: Self) -> Ordering; -} -``` -> Source code: noir_stdlib/src/cmp.nr#L102-L106 - - -`a.cmp(b)` compares two values returning `Ordering::less()` if `a < b`, -`Ordering::equal()` if `a == b`, or `Ordering::greater()` if `a > b`. -Implementing this trait on a type allows `<`, `<=`, `>`, and `>=` to be -used on values of the type. - -`std::cmp` also provides `max` and `min` functions for any type which implements the `Ord` trait. - -Implementations: - -```rust -impl Ord for u8 { .. } -impl Ord for u16 { .. } -impl Ord for u32 { .. } -impl Ord for u64 { .. } - -impl Ord for i8 { .. } -impl Ord for i16 { .. } -impl Ord for i32 { .. } - -impl Ord for i64 { .. } - -impl Ord for () { .. } -impl Ord for bool { .. } - -impl Ord for [T; N] - where T: Ord { .. } - -impl Ord for [T] - where T: Ord { .. } - -impl Ord for (A, B) - where A: Ord, B: Ord { .. } - -impl Ord for (A, B, C) - where A: Ord, B: Ord, C: Ord { .. } - -impl Ord for (A, B, C, D) - where A: Ord, B: Ord, C: Ord, D: Ord { .. } - -impl Ord for (A, B, C, D, E) - where A: Ord, B: Ord, C: Ord, D: Ord, E: Ord { .. } -``` - -## `std::ops` - -### `std::ops::Add`, `std::ops::Sub`, `std::ops::Mul`, and `std::ops::Div` - -These traits abstract over addition, subtraction, multiplication, and division respectively. -Implementing these traits for a given type will also allow that type to be used with the corresponding operator -for that trait (`+` for Add, etc) in addition to the normal method names. - -```rust title="add-trait" showLineNumbers -trait Add { - fn add(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L1-L5 - -```rust title="sub-trait" showLineNumbers -trait Sub { - fn sub(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L19-L23 - -```rust title="mul-trait" showLineNumbers -trait Mul { - fn mul(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L37-L41 - -```rust title="div-trait" showLineNumbers -trait Div { - fn div(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L55-L59 - - -The implementations block below is given for the `Add` trait, but the same types that implement -`Add` also implement `Sub`, `Mul`, and `Div`. - -Implementations: -```rust -impl Add for Field { .. } - -impl Add for i8 { .. } -impl Add for i16 { .. } -impl Add for i32 { .. } -impl Add for i64 { .. } - -impl Add for u8 { .. } -impl Add for u16 { .. } -impl Add for u32 { .. } -impl Add for u64 { .. } -``` - -### `std::ops::Rem` - -```rust title="rem-trait" showLineNumbers -trait Rem{ - fn rem(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L73-L77 - - -`Rem::rem(a, b)` is the remainder function returning the result of what is -left after dividing `a` and `b`. Implementing `Rem` allows the `%` operator -to be used with the implementation type. - -Unlike other numeric traits, `Rem` is not implemented for `Field`. - -Implementations: -```rust -impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other } } -impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other } } -impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other } } -impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other } } - -impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other } } -impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other } } -impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other } } -impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other } } -``` - -### `std::ops::Neg` - -```rust title="neg-trait" showLineNumbers -trait Neg { - fn neg(self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/arith.nr#L89-L93 - - -`Neg::neg` is equivalent to the unary negation operator `-`. - -Implementations: -```rust title="neg-trait-impls" showLineNumbers -impl Neg for Field { fn neg(self) -> Field { -self } } - -impl Neg for i8 { fn neg(self) -> i8 { -self } } -impl Neg for i16 { fn neg(self) -> i16 { -self } } -impl Neg for i32 { fn neg(self) -> i32 { -self } } -impl Neg for i64 { fn neg(self) -> i64 { -self } } -``` -> Source code: noir_stdlib/src/ops/arith.nr#L95-L102 - - -### `std::ops::Not` - -```rust title="not-trait" showLineNumbers -trait Not { - fn not(self: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L1-L5 - - -`Not::not` is equivalent to the unary bitwise NOT operator `!`. - -Implementations: -```rust title="not-trait-impls" showLineNumbers -impl Not for bool { fn not(self) -> bool { !self } } - -impl Not for u64 { fn not(self) -> u64 { !self } } -impl Not for u32 { fn not(self) -> u32 { !self } } -impl Not for u16 { fn not(self) -> u16 { !self } } -impl Not for u8 { fn not(self) -> u8 { !self } } -impl Not for u1 { fn not(self) -> u1 { !self } } - -impl Not for i8 { fn not(self) -> i8 { !self } } -impl Not for i16 { fn not(self) -> i16 { !self } } -impl Not for i32 { fn not(self) -> i32 { !self } } -impl Not for i64 { fn not(self) -> i64 { !self } } -``` -> Source code: noir_stdlib/src/ops/bit.nr#L7-L20 - - -### `std::ops::{ BitOr, BitAnd, BitXor }` - -```rust title="bitor-trait" showLineNumbers -trait BitOr { - fn bitor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L22-L26 - -```rust title="bitand-trait" showLineNumbers -trait BitAnd { - fn bitand(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L40-L44 - -```rust title="bitxor-trait" showLineNumbers -trait BitXor { - fn bitxor(self, other: Self) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L58-L62 - - -Traits for the bitwise operations `|`, `&`, and `^`. - -Implementing `BitOr`, `BitAnd` or `BitXor` for a type allows the `|`, `&`, or `^` operator respectively -to be used with the type. - -The implementations block below is given for the `BitOr` trait, but the same types that implement -`BitOr` also implement `BitAnd` and `BitXor`. - -Implementations: -```rust -impl BitOr for bool { fn bitor(self, other: bool) -> bool { self | other } } - -impl BitOr for u8 { fn bitor(self, other: u8) -> u8 { self | other } } -impl BitOr for u16 { fn bitor(self, other: u16) -> u16 { self | other } } -impl BitOr for u32 { fn bitor(self, other: u32) -> u32 { self | other } } -impl BitOr for u64 { fn bitor(self, other: u64) -> u64 { self | other } } - -impl BitOr for i8 { fn bitor(self, other: i8) -> i8 { self | other } } -impl BitOr for i16 { fn bitor(self, other: i16) -> i16 { self | other } } -impl BitOr for i32 { fn bitor(self, other: i32) -> i32 { self | other } } -impl BitOr for i64 { fn bitor(self, other: i64) -> i64 { self | other } } -``` - -### `std::ops::{ Shl, Shr }` - -```rust title="shl-trait" showLineNumbers -trait Shl { - fn shl(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L76-L80 - -```rust title="shr-trait" showLineNumbers -trait Shr { - fn shr(self, other: u8) -> Self; -} -``` -> Source code: noir_stdlib/src/ops/bit.nr#L93-L97 - - -Traits for a bit shift left and bit shift right. - -Implementing `Shl` for a type allows the left shift operator (`<<`) to be used with the implementation type. -Similarly, implementing `Shr` allows the right shift operator (`>>`) to be used with the type. - -Note that bit shifting is not currently implemented for signed types. - -The implementations block below is given for the `Shl` trait, but the same types that implement -`Shl` also implement `Shr`. - -Implementations: -```rust -impl Shl for u8 { fn shl(self, other: u8) -> u8 { self << other } } -impl Shl for u16 { fn shl(self, other: u16) -> u16 { self << other } } -impl Shl for u32 { fn shl(self, other: u32) -> u32 { self << other } } -impl Shl for u64 { fn shl(self, other: u64) -> u64 { self << other } } -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/zeroed.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/zeroed.md deleted file mode 100644 index f450fecdd36..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/noir/standard_library/zeroed.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Zeroed Function -description: - The zeroed function returns a zeroed value of any type. -keywords: - [ - zeroed - ] ---- - -Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. - -You can access the function at `std::unsafe::zeroed`. - -This function currently supports the following types: - -- Field -- Bool -- Uint -- Array -- Slice -- String -- Tuple -- Function - -Using it on other types could result in unexpected behavior. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md deleted file mode 100644 index d7249d24330..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend.md +++ /dev/null @@ -1,160 +0,0 @@ -# BarretenbergBackend - -## Extends - -- `BarretenbergVerifierBackend` - -## Implements - -- [`Backend`](../index.md#backend) - -## Constructors - -### new BarretenbergBackend(acirCircuit, options) - -```ts -new BarretenbergBackend(acirCircuit, options): BarretenbergBackend -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `acirCircuit` | `CompiledCircuit` | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergBackend`](BarretenbergBackend.md) - -#### Inherited from - -BarretenbergVerifierBackend.constructor - -## Properties - -| Property | Type | Description | Inheritance | -| :------ | :------ | :------ | :------ | -| `acirComposer` | `any` | - | BarretenbergVerifierBackend.acirComposer | -| `acirUncompressedBytecode` | `Uint8Array` | - | BarretenbergVerifierBackend.acirUncompressedBytecode | -| `api` | `Barretenberg` | - | BarretenbergVerifierBackend.api | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - | BarretenbergVerifierBackend.options | - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -#### Inherited from - -BarretenbergVerifierBackend.destroy - -*** - -### generateProof() - -```ts -generateProof(compressedWitness): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `compressedWitness` | `Uint8Array` | - -#### Returns - -`Promise`\<`ProofData`\> - -#### Description - -Generates a proof - -*** - -### generateRecursiveProofArtifacts() - -```ts -generateRecursiveProofArtifacts(proofData, numOfPublicInputs): Promise -``` - -Generates artifacts that will be passed to a circuit that will verify this proof. - -Instead of passing the proof and verification key as a byte array, we pass them -as fields which makes it cheaper to verify in a circuit. - -The proof that is passed here will have been created using a circuit -that has the #[recursive] attribute on its `main` method. - -The number of public inputs denotes how many public inputs are in the inner proof. - -#### Parameters - -| Parameter | Type | Default value | -| :------ | :------ | :------ | -| `proofData` | `ProofData` | `undefined` | -| `numOfPublicInputs` | `number` | `0` | - -#### Returns - -`Promise`\<`object`\> - -#### Example - -```typescript -const artifacts = await backend.generateRecursiveProofArtifacts(proof, numOfPublicInputs); -``` - -*** - -### getVerificationKey() - -```ts -getVerificationKey(): Promise -``` - -#### Returns - -`Promise`\<`Uint8Array`\> - -#### Inherited from - -BarretenbergVerifierBackend.getVerificationKey - -*** - -### verifyProof() - -```ts -verifyProof(proofData): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Inherited from - -BarretenbergVerifierBackend.verifyProof - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md deleted file mode 100644 index 500276ea748..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier.md +++ /dev/null @@ -1,58 +0,0 @@ -# BarretenbergVerifier - -## Constructors - -### new BarretenbergVerifier(options) - -```ts -new BarretenbergVerifier(options): BarretenbergVerifier -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `options` | [`BackendOptions`](../type-aliases/BackendOptions.md) | - -#### Returns - -[`BarretenbergVerifier`](BarretenbergVerifier.md) - -## Methods - -### destroy() - -```ts -destroy(): Promise -``` - -#### Returns - -`Promise`\<`void`\> - -*** - -### verifyProof() - -```ts -verifyProof(proofData, verificationKey): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `proofData` | `ProofData` | -| `verificationKey` | `Uint8Array` | - -#### Returns - -`Promise`\<`boolean`\> - -#### Description - -Verifies a proof - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/index.md deleted file mode 100644 index 14dfac681d4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/index.md +++ /dev/null @@ -1,40 +0,0 @@ -# backend_barretenberg - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [BarretenbergBackend](classes/BarretenbergBackend.md) | - | -| [BarretenbergVerifier](classes/BarretenbergVerifier.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [BackendOptions](type-aliases/BackendOptions.md) | - | - -## References - -### CompiledCircuit - -Renames and re-exports [Backend](index.md#backend) - -*** - -### ProofData - -Renames and re-exports [Backend](index.md#backend) - -## Variables - -### Backend - -```ts -Backend: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md deleted file mode 100644 index b49a479f4f4..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions.md +++ /dev/null @@ -1,21 +0,0 @@ -# BackendOptions - -```ts -type BackendOptions: object; -``` - -## Description - -An options object, currently only used to specify the number of threads to use. - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `memory` | `object` | - | -| `memory.maximum` | `number` | - | -| `threads` | `number` | **Description**

Number of threads | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs deleted file mode 100644 index d7d5128f9e3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/backend_barretenberg/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergBackend","label":"BarretenbergBackend"},{"type":"doc","id":"reference/NoirJS/backend_barretenberg/classes/BarretenbergVerifier","label":"BarretenbergVerifier"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/backend_barretenberg/type-aliases/BackendOptions","label":"BackendOptions"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/classes/Noir.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/classes/Noir.md deleted file mode 100644 index ead255bc504..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/classes/Noir.md +++ /dev/null @@ -1,52 +0,0 @@ -# Noir - -## Constructors - -### new Noir(circuit) - -```ts -new Noir(circuit): Noir -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `circuit` | `CompiledCircuit` | - -#### Returns - -[`Noir`](Noir.md) - -## Methods - -### execute() - -```ts -execute(inputs, foreignCallHandler?): Promise -``` - -#### Parameters - -| Parameter | Type | -| :------ | :------ | -| `inputs` | `InputMap` | -| `foreignCallHandler`? | [`ForeignCallHandler`](../type-aliases/ForeignCallHandler.md) | - -#### Returns - -`Promise`\<`object`\> - -#### Description - -Allows to execute a circuit to get its witness and return value. - -#### Example - -```typescript -async execute(inputs) -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/and.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/and.md deleted file mode 100644 index c783283e396..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/and.md +++ /dev/null @@ -1,22 +0,0 @@ -# and() - -```ts -and(lhs, rhs): string -``` - -Performs a bitwise AND operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/blake2s256.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/blake2s256.md deleted file mode 100644 index 7882d0da8d5..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/blake2s256.md +++ /dev/null @@ -1,21 +0,0 @@ -# blake2s256() - -```ts -blake2s256(inputs): Uint8Array -``` - -Calculates the Blake2s256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md deleted file mode 100644 index 5e3cd53e9d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256k1\_verify() - -```ts -ecdsa_secp256k1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256k1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md deleted file mode 100644 index 0b20ff68957..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify.md +++ /dev/null @@ -1,28 +0,0 @@ -# ecdsa\_secp256r1\_verify() - -```ts -ecdsa_secp256r1_verify( - hashed_msg, - public_key_x_bytes, - public_key_y_bytes, - signature): boolean -``` - -Verifies a ECDSA signature over the secp256r1 curve. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `hashed_msg` | `Uint8Array` | | -| `public_key_x_bytes` | `Uint8Array` | | -| `public_key_y_bytes` | `Uint8Array` | | -| `signature` | `Uint8Array` | | - -## Returns - -`boolean` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/keccak256.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/keccak256.md deleted file mode 100644 index d10f155ce86..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/keccak256.md +++ /dev/null @@ -1,21 +0,0 @@ -# keccak256() - -```ts -keccak256(inputs): Uint8Array -``` - -Calculates the Keccak256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/sha256.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/sha256.md deleted file mode 100644 index 6ba4ecac022..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/sha256.md +++ /dev/null @@ -1,21 +0,0 @@ -# sha256() - -```ts -sha256(inputs): Uint8Array -``` - -Calculates the SHA256 hash of the input bytes - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `inputs` | `Uint8Array` | | - -## Returns - -`Uint8Array` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/xor.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/xor.md deleted file mode 100644 index 8d762b895d3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/functions/xor.md +++ /dev/null @@ -1,22 +0,0 @@ -# xor() - -```ts -xor(lhs, rhs): string -``` - -Performs a bitwise XOR operation between `lhs` and `rhs` - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `lhs` | `string` | | -| `rhs` | `string` | | - -## Returns - -`string` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/index.md deleted file mode 100644 index 166508f7124..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_js - -## Exports - -### Classes - -| Class | Description | -| :------ | :------ | -| [Noir](classes/Noir.md) | - | - -### Type Aliases - -| Type alias | Description | -| :------ | :------ | -| [ErrorWithPayload](type-aliases/ErrorWithPayload.md) | - | -| [ForeignCallHandler](type-aliases/ForeignCallHandler.md) | A callback which performs an foreign call and returns the response. | -| [ForeignCallInput](type-aliases/ForeignCallInput.md) | - | -| [ForeignCallOutput](type-aliases/ForeignCallOutput.md) | - | -| [WitnessMap](type-aliases/WitnessMap.md) | - | - -### Functions - -| Function | Description | -| :------ | :------ | -| [and](functions/and.md) | Performs a bitwise AND operation between `lhs` and `rhs` | -| [blake2s256](functions/blake2s256.md) | Calculates the Blake2s256 hash of the input bytes | -| [ecdsa\_secp256k1\_verify](functions/ecdsa_secp256k1_verify.md) | Verifies a ECDSA signature over the secp256k1 curve. | -| [ecdsa\_secp256r1\_verify](functions/ecdsa_secp256r1_verify.md) | Verifies a ECDSA signature over the secp256r1 curve. | -| [keccak256](functions/keccak256.md) | Calculates the Keccak256 hash of the input bytes | -| [sha256](functions/sha256.md) | Calculates the SHA256 hash of the input bytes | -| [xor](functions/xor.md) | Performs a bitwise XOR operation between `lhs` and `rhs` | - -## References - -### CompiledCircuit - -Renames and re-exports [InputMap](index.md#inputmap) - -## Variables - -### InputMap - -```ts -InputMap: any; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md deleted file mode 100644 index e8c2f4aef3d..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ErrorWithPayload.md +++ /dev/null @@ -1,15 +0,0 @@ -# ErrorWithPayload - -```ts -type ErrorWithPayload: ExecutionError & object; -``` - -## Type declaration - -| Member | Type | Description | -| :------ | :------ | :------ | -| `decodedAssertionPayload` | `any` | - | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md deleted file mode 100644 index 812b8b16481..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallHandler.md +++ /dev/null @@ -1,24 +0,0 @@ -# ForeignCallHandler - -```ts -type ForeignCallHandler: (name, inputs) => Promise; -``` - -A callback which performs an foreign call and returns the response. - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | The identifier for the type of foreign call being performed. | -| `inputs` | [`ForeignCallInput`](ForeignCallInput.md)[] | An array of hex encoded inputs to the foreign call. | - -## Returns - -`Promise`\<[`ForeignCallOutput`](ForeignCallOutput.md)[]\> - -outputs - An array of hex encoded outputs containing the results of the foreign call. - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md deleted file mode 100644 index dd95809186a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallInput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallInput - -```ts -type ForeignCallInput: string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md deleted file mode 100644 index b71fb78a946..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/ForeignCallOutput.md +++ /dev/null @@ -1,9 +0,0 @@ -# ForeignCallOutput - -```ts -type ForeignCallOutput: string | string[]; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md deleted file mode 100644 index 258c46f9d0c..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/type-aliases/WitnessMap.md +++ /dev/null @@ -1,9 +0,0 @@ -# WitnessMap - -```ts -type WitnessMap: Map; -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs deleted file mode 100644 index b3156097df6..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_js/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"category","label":"Classes","items":[{"type":"doc","id":"reference/NoirJS/noir_js/classes/Noir","label":"Noir"}]},{"type":"category","label":"Type Aliases","items":[{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ErrorWithPayload","label":"ErrorWithPayload"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallHandler","label":"ForeignCallHandler"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallInput","label":"ForeignCallInput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/ForeignCallOutput","label":"ForeignCallOutput"},{"type":"doc","id":"reference/NoirJS/noir_js/type-aliases/WitnessMap","label":"WitnessMap"}]},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_js/functions/and","label":"and"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/blake2s256","label":"blake2s256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256k1_verify","label":"ecdsa_secp256k1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/ecdsa_secp256r1_verify","label":"ecdsa_secp256r1_verify"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/keccak256","label":"keccak256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/sha256","label":"sha256"},{"type":"doc","id":"reference/NoirJS/noir_js/functions/xor","label":"xor"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/.nojekyll b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/.nojekyll deleted file mode 100644 index e2ac6616add..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/.nojekyll +++ /dev/null @@ -1 +0,0 @@ -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile.md deleted file mode 100644 index 6faf763b37f..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile() - -```ts -compile( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ProgramCompilationArtifacts`](../index.md#programcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_program(fm); -``` - -```typescript -// Browser - -import { compile_program, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_program(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile_contract.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile_contract.md deleted file mode 100644 index 7d0b39a43ef..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/compile_contract.md +++ /dev/null @@ -1,51 +0,0 @@ -# compile\_contract() - -```ts -compile_contract( - fileManager, - projectPath?, - logFn?, -debugLogFn?): Promise -``` - -Compiles a Noir project - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `fileManager` | `FileManager` | The file manager to use | -| `projectPath`? | `string` | The path to the project inside the file manager. Defaults to the root of the file manager | -| `logFn`? | `LogFn` | A logging function. If not provided, console.log will be used | -| `debugLogFn`? | `LogFn` | A debug logging function. If not provided, logFn will be used | - -## Returns - -`Promise`\<[`ContractCompilationArtifacts`](../index.md#contractcompilationartifacts)\> - -## Example - -```typescript -// Node.js - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager(myProjectPath); -const myCompiledCode = await compile_contract(fm); -``` - -```typescript -// Browser - -import { compile_contract, createFileManager } from '@noir-lang/noir_wasm'; - -const fm = createFileManager('/'); -for (const path of files) { - await fm.writeFile(path, await getFileAsStream(path)); -} -const myCompiledCode = await compile_contract(fm); -``` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/createFileManager.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/createFileManager.md deleted file mode 100644 index 7e65c1d69c7..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/createFileManager.md +++ /dev/null @@ -1,21 +0,0 @@ -# createFileManager() - -```ts -createFileManager(dataDir): FileManager -``` - -Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `dataDir` | `string` | root of the file system | - -## Returns - -`FileManager` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md deleted file mode 100644 index fcea9275341..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/functions/inflateDebugSymbols.md +++ /dev/null @@ -1,21 +0,0 @@ -# inflateDebugSymbols() - -```ts -inflateDebugSymbols(debugSymbols): any -``` - -Decompresses and decodes the debug symbols - -## Parameters - -| Parameter | Type | Description | -| :------ | :------ | :------ | -| `debugSymbols` | `string` | The base64 encoded debug symbols | - -## Returns - -`any` - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/index.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/index.md deleted file mode 100644 index b6e0f9d1bc0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/index.md +++ /dev/null @@ -1,49 +0,0 @@ -# noir_wasm - -## Exports - -### Functions - -| Function | Description | -| :------ | :------ | -| [compile](functions/compile.md) | Compiles a Noir project | -| [compile\_contract](functions/compile_contract.md) | Compiles a Noir project | -| [createFileManager](functions/createFileManager.md) | Creates a new FileManager instance based on fs in node and memfs in the browser (via webpack alias) | -| [inflateDebugSymbols](functions/inflateDebugSymbols.md) | Decompresses and decodes the debug symbols | - -## References - -### compile\_program - -Renames and re-exports [compile](functions/compile.md) - -## Interfaces - -### ContractCompilationArtifacts - -The compilation artifacts of a given contract. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `contract` | `ContractArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -### ProgramCompilationArtifacts - -The compilation artifacts of a given program. - -#### Properties - -| Property | Type | Description | -| :------ | :------ | :------ | -| `name` | `string` | not part of the compilation output, injected later | -| `program` | `ProgramArtifact` | The compiled contract. | -| `warnings` | `unknown`[] | Compilation warnings. | - -*** - -Generated using [typedoc-plugin-markdown](https://www.npmjs.com/package/typedoc-plugin-markdown) and [TypeDoc](https://typedoc.org/) diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs deleted file mode 100644 index e0870710349..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/NoirJS/noir_wasm/typedoc-sidebar.cjs +++ /dev/null @@ -1,4 +0,0 @@ -// @ts-check -/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ -const typedocSidebar = { items: [{"type":"doc","id":"reference/NoirJS/noir_wasm/index","label":"API"},{"type":"category","label":"Functions","items":[{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile","label":"compile"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/compile_contract","label":"compile_contract"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/createFileManager","label":"createFileManager"},{"type":"doc","id":"reference/NoirJS/noir_wasm/functions/inflateDebugSymbols","label":"inflateDebugSymbols"}]}]}; -module.exports = typedocSidebar.items; \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/_category_.json deleted file mode 100644 index 5b6a20a609a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/_category_.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "position": 4, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/_category_.json b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/_category_.json deleted file mode 100644 index 27869205ad3..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/_category_.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "label": "Debugger", - "position": 1, - "collapsible": true, - "collapsed": true -} diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_known_limitations.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_known_limitations.md deleted file mode 100644 index 936d416ac4b..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_known_limitations.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -title: Known limitations -description: - An overview of known limitations of the current version of the Noir debugger -keywords: - [ - Nargo, - Noir Debugger, - VS Code, - ] -sidebar_position: 2 ---- - -# Debugger Known Limitations - -There are currently some limits to what the debugger can observe. - -## Mutable references - -The debugger is currently blind to any state mutated via a mutable reference. For example, in: - -``` -let mut x = 1; -let y = &mut x; -*y = 2; -``` - -The update on `x` will not be observed by the debugger. That means, when running `vars` from the debugger REPL, or inspecting the _local variables_ pane in the VS Code debugger, `x` will appear with value 1 despite having executed `*y = 2;`. - -## Variables of type function or mutable references are opaque - -When inspecting variables, any variable of type `Function` or `MutableReference` will render its value as `<>` or `<>`. - -## Debugger instrumentation affects resulting ACIR - -In order to make the state of local variables observable, the debugger compiles Noir circuits interleaving foreign calls that track any mutations to them. While this works (except in the cases described above) and doesn't introduce any behavior changes, it does as a side effect produce bigger bytecode. In particular, when running the command `opcodes` on the REPL debugger, you will notice Unconstrained VM blocks that look like this: - -``` -... -5 BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [], q_c: 2 }), Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(2))], q_c: 0 })] - | outputs=[] - 5.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 5.1 | Mov { destination: RegisterIndex(3), source: RegisterIndex(1) } - 5.2 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 5.3 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 5.4 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 5.5 | Mov { destination: RegisterIndex(3), source: RegisterIndex(3) } - 5.6 | Call { location: 8 } - 5.7 | Stop - 5.8 | ForeignCall { function: "__debug_var_assign", destinations: [], inputs: [RegisterIndex(RegisterIndex(2)), RegisterIndex(RegisterIndex(3))] } -... -``` - -If you are interested in debugging/inspecting compiled ACIR without these synthetic changes, you can invoke the REPL debugger with the `--skip-instrumentation` flag or launch the VS Code debugger with the `skipConfiguration` property set to true in its launch configuration. You can find more details about those in the [Debugger REPL reference](debugger_repl.md) and the [VS Code Debugger reference](debugger_vscode.md). - -:::note -Skipping debugger instrumentation means you won't be able to inspect values of local variables. -::: - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_repl.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_repl.md deleted file mode 100644 index 46e2011304e..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_repl.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -title: REPL Debugger -description: - Noir Debugger REPL options and commands. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - REPL, - ] -sidebar_position: 1 ---- - -## Running the REPL debugger - -`nargo debug [OPTIONS] [WITNESS_NAME]` - -Runs the Noir REPL debugger. If a `WITNESS_NAME` is provided the debugger writes the resulting execution witness to a `WITNESS_NAME` file. - -### Options - -| Option | Description | -| --------------------- | ------------------------------------------------------------ | -| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover]| -| `--package ` | The name of the package to debug | -| `--print-acir` | Display the ACIR for compiled circuit | -| `--deny-warnings` | Treat all warnings as errors | -| `--silence-warnings` | Suppress warnings | -| `-h, --help` | Print help | - -None of these options are required. - -:::note -Since the debugger starts by compiling the target package, all Noir compiler options are also available. Check out the [compiler reference](../nargo_commands.md#nargo-compile) to learn more about the compiler options. -::: - -## REPL commands - -Once the debugger is running, it accepts the following commands. - -#### `help` (h) - -Displays the menu of available commands. - -``` -> help -Available commands: - - opcodes display ACIR opcodes - into step into to the next opcode - next step until a new source location is reached - out step until a new source location is reached - and the current stack frame is finished - break LOCATION:OpcodeLocation add a breakpoint at an opcode location - over step until a new source location is reached - without diving into function calls - restart restart the debugging session - delete LOCATION:OpcodeLocation delete breakpoint at an opcode location - witness show witness map - witness index:u32 display a single witness from the witness map - witness index:u32 value:String update a witness with the given value - memset index:usize value:String update a memory cell with the given - value - continue continue execution until the end of the - program - vars show variable values available at this point - in execution - stacktrace display the current stack trace - memory show memory (valid when executing unconstrained code) value - step step to the next ACIR opcode - -Other commands: - - help Show this help message - quit Quit repl - -``` - -### Stepping through programs - -#### `next` (n) - -Step until the next Noir source code location. While other commands, such as [`into`](#into-i) and [`step`](#step-s), allow for finer grained control of the program's execution at the opcode level, `next` is source code centric. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `next` here would cause the debugger to jump to the definition of `deep_entry_point` (if available). - -If you want to step over `deep_entry_point` and go straight to line 8, use [the `over` command](#over) instead. - -#### `over` - -Step until the next source code location, without diving into function calls. For example: - -``` -3 ... -4 fn main(x: u32) { -5 assert(entry_point(x) == 2); -6 swap_entry_point(x, x + 1); -7 -> assert(deep_entry_point(x) == 4); -8 multiple_values_entry_point(x); -9 } -``` - - -Using `over` here would cause the debugger to execute until line 8 (`multiple_values_entry_point(x);`). - -If you want to step into `deep_entry_point` instead, use [the `next` command](#next-n). - -#### `out` - -Step until the end of the current function call. For example: - -``` - 3 ... - 4 fn main(x: u32) { - 5 assert(entry_point(x) == 2); - 6 swap_entry_point(x, x + 1); - 7 -> assert(deep_entry_point(x) == 4); - 8 multiple_values_entry_point(x); - 9 } - 10 - 11 unconstrained fn returns_multiple_values(x: u32) -> (u32, u32, u32, u32) { - 12 ... - ... - 55 - 56 unconstrained fn deep_entry_point(x: u32) -> u32 { - 57 -> level_1(x + 1) - 58 } - -``` - -Running `out` here will resume execution until line 8. - -#### `step` (s) - -Skips to the next ACIR code. A compiled Noir program is a sequence of ACIR opcodes. However, an unconstrained VM opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `step` command at this point would result in the debugger stopping at ACIR opcode 2, `EXPR`, skipping unconstrained computation steps. - -Use [the `into` command](#into-i) instead if you want to follow unconstrained computation step by step. - -#### `into` (i) - -Steps into the next opcode. A compiled Noir program is a sequence of ACIR opcodes. However, a BRILLIG opcode denotes the start of an unconstrained code block, to be executed by the unconstrained VM. For example (redacted for brevity): - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -The `->` here shows the debugger paused at an ACIR opcode: `BRILLIG`, at index 1, which denotes an unconstrained code block is about to start. - -Using the `into` command at this point would result in the debugger stopping at opcode 1.0, `Mov ...`, allowing the debugger user to follow unconstrained computation step by step. - -Use [the `step` command](#step-s) instead if you want to skip to the next ACIR code directly. - -#### `continue` (c) - -Continues execution until the next breakpoint, or the end of the program. - -#### `restart` (res) - -Interrupts execution, and restarts a new debugging session from scratch. - -#### `opcodes` (o) - -Display the program's ACIR opcode sequence. For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -### Breakpoints - -#### `break [Opcode]` (or shorthand `b [Opcode]`) - -Sets a breakpoint on the specified opcode index. To get a list of the program opcode numbers, see [the `opcode` command](#opcodes-o). For example: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -In this example, issuing a `break 1.2` command adds break on opcode 1.2, as denoted by the `*` character: - -``` -0 BLACKBOX::RANGE [(_0, num_bits: 32)] [ ] -1 -> BRILLIG inputs=[Single(Expression { mul_terms: [], linear_combinations: [(1, Witness(0))], q_c: 0 })] outputs=[Simple(Witness(1))] - 1.0 | Mov { destination: RegisterIndex(2), source: RegisterIndex(0) } - 1.1 | Const { destination: RegisterIndex(0), value: Value { inner: 0 } } - 1.2 | * Const { destination: RegisterIndex(1), value: Value { inner: 0 } } - 1.3 | Mov { destination: RegisterIndex(2), source: RegisterIndex(2) } - 1.4 | Call { location: 7 } - ... - 1.43 | Return -2 EXPR [ (1, _1) -2 ] -``` - -Running [the `continue` command](#continue-c) at this point would cause the debugger to execute the program until opcode 1.2. - -#### `delete [Opcode]` (or shorthand `d [Opcode]`) - -Deletes a breakpoint at an opcode location. Usage is analogous to [the `break` command](#). - -### Variable inspection - -#### vars - -Show variable values available at this point in execution. - -:::note -The ability to inspect variable values from the debugger depends on compilation to be run in a special debug instrumentation mode. This instrumentation weaves variable tracing code with the original source code. - -So variable value inspection comes at the expense of making the resulting ACIR bytecode bigger and harder to understand and optimize. - -If you find this compromise unacceptable, you can run the debugger with the flag `--skip-debug-instrumentation`. This will compile your circuit without any additional debug information, so the resulting ACIR bytecode will be identical to the one produced by standard Noir compilation. However, if you opt for this, the `vars` command will not be available while debugging. -::: - - -### Stacktrace - -#### `stacktrace` - -Displays the current stack trace. - - -### Witness map - -#### `witness` (w) - -Show witness map. For example: - -``` -_0 = 0 -_1 = 2 -_2 = 1 -``` - -#### `witness [Witness Index]` - -Display a single witness from the witness map. For example: - -``` -> witness 1 -_1 = 2 -``` - -#### `witness [Witness Index] [New value]` - -Overwrite the given index with a new value. For example: - -``` -> witness 1 3 -_1 = 3 -``` - - -### Unconstrained VM memory - -#### `memory` - -Show unconstrained VM memory state. For example: - -``` -> memory -At opcode 1.13: Store { destination_pointer: RegisterIndex(0), source: RegisterIndex(3) } -... -> registers -0 = 0 -1 = 10 -2 = 0 -3 = 1 -4 = 1 -5 = 2³² -6 = 1 -> into -At opcode 1.14: Const { destination: RegisterIndex(5), value: Value { inner: 1 } } -... -> memory -0 = 1 -> -``` - -In the example above: we start with clean memory, then step through a `Store` opcode which stores the value of register 3 (1) into the memory address stored in register 0 (0). Thus now `memory` shows memory address 0 contains value 1. - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: - -#### `memset [Memory address] [New value]` - -Update a memory cell with the given value. For example: - -``` -> memory -0 = 1 -> memset 0 2 -> memory -0 = 2 -> memset 1 4 -> memory -0 = 2 -1 = 4 -> -``` - -:::note -This command is only functional while the debugger is executing unconstrained code. -::: \ No newline at end of file diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_vscode.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_vscode.md deleted file mode 100644 index c027332b3b0..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/debugger/debugger_vscode.md +++ /dev/null @@ -1,82 +0,0 @@ ---- -title: VS Code Debugger -description: - VS Code Debugger configuration and features. -keywords: - [ - Nargo, - Noir CLI, - Noir Debugger, - VS Code, - IDE, - ] -sidebar_position: 0 ---- - -# VS Code Noir Debugger Reference - -The Noir debugger enabled by the vscode-noir extension ships with default settings such that the most common scenario should run without any additional configuration steps. - -These defaults can nevertheless be overridden by defining a launch configuration file. This page provides a reference for the properties you can override via a launch configuration file, as well as documenting the Nargo `dap` command, which is a dependency of the VS Code Noir debugger. - - -## Creating and editing launch configuration files - -To create a launch configuration file from VS Code, open the _debug pane_, and click on _create a launch.json file_. - -![Creating a launch configuration file](@site/static/img/debugger/ref1-create-launch.png) - -A `launch.json` file will be created, populated with basic defaults. - -### Noir Debugger launch.json properties - -#### projectFolder - -_String, optional._ - -Absolute path to the Nargo project to debug. By default, it is dynamically determined by looking for the nearest `Nargo.toml` file to the active file at the moment of launching the debugger. - -#### proverName - -_String, optional._ - -Name of the prover input to use. Defaults to `Prover`, which looks for a file named `Prover.toml` at the `projectFolder`. - -#### generateAcir - -_Boolean, optional._ - -If true, generate ACIR opcodes instead of unconstrained opcodes which will be closer to release binaries but less convenient for debugging. Defaults to `false`. - -#### skipInstrumentation - -_Boolean, optional._ - -Skips variables debugging instrumentation of code, making debugging less convenient but the resulting binary smaller and closer to production. Defaults to `false`. - -:::note -Skipping instrumentation causes the debugger to be unable to inspect local variables. -::: - -## `nargo dap [OPTIONS]` - -When run without any option flags, it starts the Nargo Debug Adapter Protocol server, which acts as the debugging backend for the VS Code Noir Debugger. - -All option flags are related to preflight checks. The Debug Adapter Protocol specifies how errors are to be informed from a running DAP server, but it doesn't specify mechanisms to communicate server initialization errors between the DAP server and its client IDE. - -Thus `nargo dap` ships with a _preflight check_ mode. If flag `--preflight-check` and the rest of the `--preflight-*` flags are provided, Nargo will run the same initialization routine except it will not start the DAP server. - -`vscode-noir` will then run `nargo dap` in preflight check mode first before a debugging session starts. If the preflight check ends in error, vscode-noir will present stderr and stdout output from this process through its own Output pane in VS Code. This makes it possible for users to diagnose what pieces of configuration might be wrong or missing in case of initialization errors. - -If the preflight check succeeds, `vscode-noir` proceeds to start the DAP server normally but running `nargo dap` without any additional flags. - -### Options - -| Option | Description | -| --------------------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `--preflight-check` | If present, dap runs in preflight check mode. | -| `--preflight-project-folder ` | Absolute path to the project to debug for preflight check. | -| `--preflight-prover-name ` | Name of prover file to use for preflight check | -| `--preflight-generate-acir` | Optional. If present, compile in ACIR mode while running preflight check. | -| `--preflight-skip-instrumentation` | Optional. If present, compile without introducing debug instrumentation while running preflight check. | -| `-h, --help` | Print help. | diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/nargo_commands.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/nargo_commands.md deleted file mode 100644 index ab9dd879d85..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/reference/nargo_commands.md +++ /dev/null @@ -1,244 +0,0 @@ ---- -title: Nargo -description: - Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, - generate Solidity verifier smart contract and compile into JSON file containing ACIR - representation and ABI of circuit. -keywords: - [ - Nargo, - Noir CLI, - Noir Prover, - Noir Verifier, - generate Solidity verifier, - compile JSON file, - ACIR representation, - ABI of circuit, - TypeScript, - ] -sidebar_position: 0 ---- - -# Command-Line Help for `nargo` - -This document contains the help content for the `nargo` command-line program. - -**Command Overview:** - -* [`nargo`↴](#nargo) -* [`nargo check`↴](#nargo-check) -* [`nargo fmt`↴](#nargo-fmt) -* [`nargo compile`↴](#nargo-compile) -* [`nargo new`↴](#nargo-new) -* [`nargo init`↴](#nargo-init) -* [`nargo execute`↴](#nargo-execute) -* [`nargo test`↴](#nargo-test) -* [`nargo info`↴](#nargo-info) -* [`nargo lsp`↴](#nargo-lsp) - -## `nargo` - -Noir's package manager - -**Usage:** `nargo ` - -###### **Subcommands:** - -* `check` — Checks the constraint system for errors -* `fmt` — Format the Noir files in a workspace -* `compile` — Compile the program and its secret execution trace into ACIR format -* `new` — Create a Noir project in a new directory -* `init` — Create a Noir project in the current directory -* `execute` — Executes a circuit to calculate its return value -* `test` — Run the tests for this program -* `info` — Provides detailed information on each of a program's function (represented by a single circuit) -* `lsp` — Starts the Noir LSP server - -###### **Options:** - - - - -## `nargo check` - -Checks the constraint system for errors - -**Usage:** `nargo check [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to check -* `--workspace` — Check all packages in the workspace -* `--overwrite` — Force overwrite of existing files -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo fmt` - -Format the Noir files in a workspace - -**Usage:** `nargo fmt [OPTIONS]` - -###### **Options:** - -* `--check` — Run noirfmt in check mode - - - -## `nargo compile` - -Compile the program and its secret execution trace into ACIR format - -**Usage:** `nargo compile [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to compile -* `--workspace` — Compile all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo new` - -Create a Noir project in a new directory - -**Usage:** `nargo new [OPTIONS] ` - -###### **Arguments:** - -* `` — The path to save the new project - -###### **Options:** - -* `--name ` — Name of the package [default: package directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo init` - -Create a Noir project in the current directory - -**Usage:** `nargo init [OPTIONS]` - -###### **Options:** - -* `--name ` — Name of the package [default: current directory name] -* `--lib` — Use a library template -* `--bin` — Use a binary template [default] -* `--contract` — Use a contract template - - - -## `nargo execute` - -Executes a circuit to calculate its return value - -**Usage:** `nargo execute [OPTIONS] [WITNESS_NAME]` - -###### **Arguments:** - -* `` — Write the execution witness to named file - -###### **Options:** - -* `-p`, `--prover-name ` — The name of the toml file which contains the inputs for the prover - - Default value: `Prover` -* `--package ` — The name of the package to execute -* `--workspace` — Execute all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo test` - -Run the tests for this program - -**Usage:** `nargo test [OPTIONS] [TEST_NAME]` - -###### **Arguments:** - -* `` — If given, only tests with names containing this string will be run - -###### **Options:** - -* `--show-output` — Display output of `println` statements -* `--exact` — Only run tests that match exactly -* `--package ` — The name of the package to test -* `--workspace` — Test all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings -* `--oracle-resolver ` — JSON RPC url to solve oracle calls - - - -## `nargo info` - -Provides detailed information on each of a program's function (represented by a single circuit) - -Current information provided per circuit: 1. The number of ACIR opcodes 2. Counts the final number gates in the circuit used by a backend - -**Usage:** `nargo info [OPTIONS]` - -###### **Options:** - -* `--package ` — The name of the package to detail -* `--workspace` — Detail all packages in the workspace -* `--expression-width ` — Override the expression width requested by the backend - - Default value: `4` -* `--force` — Force a full recompilation -* `--print-acir` — Display the ACIR for compiled circuit -* `--deny-warnings` — Treat all warnings as errors -* `--silence-warnings` — Suppress warnings - - - -## `nargo lsp` - -Starts the Noir LSP server - -Starts an LSP server which allows IDEs such as VS Code to display diagnostics in Noir source. - -VS Code Noir Language Support: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir - -**Usage:** `nargo lsp` - - - -
- - - This document was generated automatically by - clap-markdown. - - diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/debugger.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/debugger.md deleted file mode 100644 index 9b7565ba9ff..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/debugger.md +++ /dev/null @@ -1,26 +0,0 @@ ---- -title: Debugger -description: Learn about the Noir Debugger, in its REPL or VS Code versions. -keywords: [Nargo, VSCode, Visual Studio Code, REPL, Debugger] -sidebar_position: 2 ---- - -# Noir Debugger - -There are currently two ways of debugging Noir programs: - -1. From VS Code, via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). -2. Via the REPL debugger, which ships with Nargo. - -In order to use either version of the debugger, you will need to install recent enough versions of Noir, [Nargo](../getting_started/installation/index.md) and vscode-noir: - -- Noir & Nargo ≥0.28.0 -- Noir's VS Code extension ≥0.0.11 - -:::info -At the moment, the debugger supports debugging binary projects, but not contracts. -::: - -We cover the VS Code Noir debugger more in depth in [its VS Code debugger how-to guide](../how_to/debugger/debugging_with_vs_code.md) and [the reference](../reference/debugger/debugger_vscode.md). - -The REPL debugger is discussed at length in [the REPL debugger how-to guide](../how_to/debugger/debugging_with_the_repl.md) and [the reference](../reference/debugger/debugger_repl.md). diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/language_server.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/language_server.md deleted file mode 100644 index 81e0356ef8a..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/language_server.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -title: Language Server -description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. -keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] -sidebar_position: 0 ---- - -This section helps you install and configure the Noir Language Server. - -The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. - -## Language Server - -The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. -As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! - -If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. - -## Language Client - -The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. - -Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). - -> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). -> -> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. - -When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: - -![Compile and Execute](@site/static/img/codelens_compile_execute.png) -![Run test](@site/static/img/codelens_run_test.png) - -You should also see your tests in the `testing` panel: - -![Testing panel](@site/static/img/codelens_testing_panel.png) - -### Configuration - -- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. -- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. -- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. -- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/testing.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/testing.md deleted file mode 100644 index d3e0c522473..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tooling/testing.md +++ /dev/null @@ -1,62 +0,0 @@ ---- -title: Testing in Noir -description: Learn how to use Nargo to test your Noir program in a quick and easy way -keywords: [Nargo, testing, Noir, compile, test] -sidebar_position: 1 ---- - -You can test your Noir programs using Noir circuits. - -Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if -you run `nargo test`. - -For example if you have a program like: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test] -fn test_add() { - assert(add(2,2) == 4); - assert(add(0,1) == 1); - assert(add(1,0) == 1); -} -``` - -Running `nargo test` will test that the `test_add` function can be executed while satisfying all -the constraints which allows you to test that add returns the expected values. Test functions can't -have any arguments currently. - -### Test fail - -You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: - -```rust -fn add(x: u64, y: u64) -> u64 { - x + y -} -#[test(should_fail)] -fn test_add() { - assert(add(2,2) == 5); -} -``` - -You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: - -```rust -fn main(african_swallow_avg_speed : Field) { - assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); -} - -#[test] -fn test_king_arthur() { - main(65); -} - -#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] -fn test_bridgekeeper() { - main(32); -} - -``` diff --git a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tutorials/noirjs_app.md b/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tutorials/noirjs_app.md deleted file mode 100644 index 8c23b639f12..00000000000 --- a/noir/noir-repo/docs/versioned_docs/version-v0.31.0/tutorials/noirjs_app.md +++ /dev/null @@ -1,348 +0,0 @@ ---- -title: Building a web app with NoirJS -description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment. -keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs, app] -sidebar_position: 0 -pagination_next: noir/concepts/data_types/index ---- - -NoirJS is a set of packages meant to work both in a browser and a server environment. In this tutorial, we will build a simple web app using them. From here, you should get an idea on how to proceed with your own Noir projects! - -You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). - -## Setup - -:::note - -Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.31.x matches `noir_js@0.31.x`, etc. - -In this guide, we will be pinned to 0.31.0. - -::: - -Before we start, we want to make sure we have Node, Nargo and the Barretenberg proving system (`bb`) installed. - -We start by opening a terminal and executing `node --version`. If we don't get an output like `v20.10.0`, that means node is not installed. Let's do that by following the handy [nvm guide](https://github.com/nvm-sh/nvm?tab=readme-ov-file#install--update-script). - -As for `Nargo`, we can follow the [Nargo guide](../getting_started/installation/index.md) to install it. If you're lazy, just paste this on a terminal and run `noirup`: - -```sh -curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash -``` - -Follow the instructions on [this page](https://github.com/AztecProtocol/aztec-packages/tree/master/barretenberg/cpp/src/barretenberg/bb#installation) to install `bb`. -Version 0.41.0 is compatible with `nargo` version 0.31.0, which you can install with `bbup -v 0.41.0` once `bbup` is installed. - -Easy enough. Onwards! - -## Our project - -ZK is a powerful technology. An app that doesn't reveal one of the inputs to _anyone_ is almost unbelievable, yet Noir makes it as easy as a single line of code. - -In fact, it's so simple that it comes nicely packaged in `nargo`. Let's do that! - -### Nargo - -Run: - -```bash -nargo new circuit -``` - -And... That's about it. Your program is ready to be compiled and run. - -To compile, let's `cd` into the `circuit` folder to enter our project, and call: - -```bash -nargo compile -``` - -This compiles our circuit into `json` format and add it to a new `target` folder. - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit <---- our working directory - ├── Nargo.toml - ├── src - │ └── main.nr - └── target - └── circuit.json -``` - -::: - -### Node and Vite - -If you want to explore Nargo, feel free to go on a side-quest now and follow the steps in the -[getting started](../getting_started/hello_noir/index.md) guide. However, we want our app to run on the browser, so we need Vite. - -Vite is a powerful tool to generate static websites. While it provides all kinds of features, let's just go barebones with some good old vanilla JS. - -To do this this, go back to the previous folder (`cd ..`) and create a new vite project by running `npm create vite` and choosing "Vanilla" and "Javascript". - -A wild `vite-project` directory should now appear in your root folder! Let's not waste any time and dive right in: - -```bash -cd vite-project -``` - -### Setting Up Vite and Configuring the Project - -Before we proceed with any coding, let's get our environment tailored for Noir. We'll start by laying down the foundations with a `vite.config.js` file. This little piece of configuration is our secret sauce for making sure everything meshes well with the NoirJS libraries and other special setups we might need, like handling WebAssembly modules. Here’s how you get that going: - -#### Creating the vite.config.js - -In your freshly minted `vite-project` folder, create a new file named `vite.config.js` and open it in your code editor. Paste the following to set the stage: - -```javascript -import { defineConfig } from 'vite'; -import copy from 'rollup-plugin-copy'; -import fs from 'fs'; -import path from 'path'; - -const wasmContentTypePlugin = { - name: 'wasm-content-type-plugin', - configureServer(server) { - server.middlewares.use(async (req, res, next) => { - if (req.url.endsWith('.wasm')) { - res.setHeader('Content-Type', 'application/wasm'); - const newPath = req.url.replace('deps', 'dist'); - const targetPath = path.join(__dirname, newPath); - const wasmContent = fs.readFileSync(targetPath); - return res.end(wasmContent); - } - next(); - }); - }, -}; - -export default defineConfig(({ command }) => { - if (command === 'serve') { - return { - build: { - target: 'esnext', - rollupOptions: { - external: ['@aztec/bb.js'] - } - }, - optimizeDeps: { - esbuildOptions: { - target: 'esnext' - } - }, - plugins: [ - copy({ - targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], - copySync: true, - hook: 'buildStart', - }), - command === 'serve' ? wasmContentTypePlugin : [], - ], - }; - } - - return {}; -}); -``` - -#### Install Dependencies - -Now that our stage is set, install the necessary NoirJS packages along with our other dependencies: - -```bash -npm install && npm install @noir-lang/backend_barretenberg@0.31.0 @noir-lang/noir_js@0.31.0 -npm install rollup-plugin-copy --save-dev -``` - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...etc... -└── vite-project <---- our working directory - └── ...etc... -``` - -::: - -#### Some cleanup - -`npx create vite` is amazing but it creates a bunch of files we don't really need for our simple example. Actually, let's just delete everything except for `vite.config.js`, `index.html`, `main.js` and `package.json`. I feel lighter already. - -![my heart is ready for you, noir.js](@site/static/img/memes/titanic.jpeg) - -## HTML - -Our app won't run like this, of course. We need some working HTML, at least. Let's open our broken-hearted `index.html` and replace everything with this code snippet: - -```html - - - - - - -

Noir app

-
- - -
-
-

Logs

-

Proof

-
- - -``` - -It _could_ be a beautiful UI... Depending on which universe you live in. - -## Some good old vanilla Javascript - -Our love for Noir needs undivided attention, so let's just open `main.js` and delete everything (this is where the romantic scenery becomes a bit creepy). - -Start by pasting in this boilerplate code: - -```js -function display(container, msg) { - const c = document.getElementById(container); - const p = document.createElement('p'); - p.textContent = msg; - c.appendChild(p); -} - -document.getElementById('submitGuess').addEventListener('click', async () => { - try { - // here's where love happens - } catch (err) { - display('logs', 'Oh 💔 Wrong guess'); - } -}); -``` - -The display function doesn't do much. We're simply manipulating our website to see stuff happening. For example, if the proof fails, it will simply log a broken heart 😢 - -:::info - -At this point in the tutorial, your folder structure should look like this: - -```tree -. -└── circuit - └── ...same as above -└── vite-project - ├── vite.config.js - ├── main.js - ├── package.json - └── index.html -``` - -You'll see other files and folders showing up (like `package-lock.json`, `node_modules`) but you shouldn't have to care about those. - -::: - -## Some NoirJS - -We're starting with the good stuff now. If you've compiled the circuit as described above, you should have a `json` file we want to import at the very top of our `main.js` file: - -```ts -import circuit from '../circuit/target/circuit.json'; -``` - -[Noir is backend-agnostic](../index.mdx#whats-new-about-noir). We write Noir, but we also need a proving backend. That's why we need to import and instantiate the two dependencies we installed above: `BarretenbergBackend` and `Noir`. Let's import them right below: - -```js -import { BarretenbergBackend, BarretenbergVerifier as Verifier } from '@noir-lang/backend_barretenberg'; -import { Noir } from '@noir-lang/noir_js'; -``` - -And instantiate them inside our try-catch block: - -```ts -// try { -const backend = new BarretenbergBackend(circuit); -const noir = new Noir(circuit); -// } -``` - -:::note - -For the remainder of the tutorial, everything will be happening inside the `try` block - -::: - -## Our app - -Now for the app itself. We're capturing whatever is in the input when people press the submit button. Just add this: - -```js -const x = parseInt(document.getElementById('guessInput').value); -const input = { x, y: 2 }; -``` - -Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: - -```js -await setup(); // let's squeeze our wasm inits here - -display('logs', 'Generating proof... ⌛'); -const { witness } = await noir.execute(input); -const proof = await backend.generateProof(witness); -display('logs', 'Generating proof... ✅'); -display('results', proof.proof); -``` - -You're probably eager to see stuff happening, so go and run your app now! - -From your terminal, run `npm run dev`. If it doesn't open a browser for you, just visit `localhost:5173`. You should now see the worst UI ever, with an ugly input. - -![Getting Started 0](@site/static/img/noir_getting_started_1.png) - -Now, our circuit says `fn main(x: Field, y: pub Field)`. This means only the `y` value is public, and it's hardcoded above: `input = { x, y: 2 }`. In other words, you won't need to send your secret`x` to the verifier! - -By inputting any number other than 2 in the input box and clicking "submit", you should get a valid proof. Otherwise the proof won't even generate correctly. By the way, if you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human ❤️. - -## Verifying - -Time to celebrate, yes! But we shouldn't trust machines so blindly. Let's add these lines to see our proof being verified: - -```js -display('logs', 'Verifying proof... ⌛'); -const isValid = await backend.verifyProof(proof); - -// or to cache and use the verification key: -// const verificationKey = await backend.getVerificationKey(); -// const verifier = new Verifier(); -// const isValid = await verifier.verifyProof(proof, verificationKey); - -if (isValid) display('logs', 'Verifying proof... ✅'); -``` - -You have successfully generated a client-side Noir web app! - -![coded app without math knowledge](@site/static/img/memes/flextape.jpeg) - -## Further Reading - -You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/vite-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. - -You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.17.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.17.0-sidebars.json deleted file mode 100644 index a9ec39925d9..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.17.0-sidebars.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/reference" - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.19.0-sidebars.json deleted file mode 100644 index a9ec39925d9..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.0-sidebars.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/reference" - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.1-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.19.1-sidebars.json deleted file mode 100644 index 6823055c5d3..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.1-sidebars.json +++ /dev/null @@ -1,288 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "category", - "label": "Noir JS", - "link": { - "type": "doc", - "id": "noir_js/reference/noir_js/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/classes/Noir", - "label": "Noir" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallHandler", - "label": "ForeignCallHandler" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallInput", - "label": "ForeignCallInput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallOutput", - "label": "ForeignCallOutput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ProofData", - "label": "ProofData" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/WitnessMap", - "label": "WitnessMap" - } - ] - }, - { - "type": "category", - "label": "Functions", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/and", - "label": "and" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/blake2s256", - "label": "blake2s256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify", - "label": "ecdsa_secp256k1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify", - "label": "ecdsa_secp256r1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/keccak256", - "label": "keccak256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/sha256", - "label": "sha256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/xor", - "label": "xor" - } - ] - } - ] - }, - { - "type": "category", - "label": "Backend Barretenberg", - "link": { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/classes/BarretenbergBackend", - "label": "BarretenbergBackend" - } - ] - }, - { - "type": "category", - "label": "Interfaces", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/interfaces/Backend", - "label": "Backend" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/BackendOptions", - "label": "BackendOptions" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/ProofData", - "label": "ProofData" - } - ] - } - ] - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.2-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.19.2-sidebars.json deleted file mode 100644 index 6823055c5d3..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.2-sidebars.json +++ /dev/null @@ -1,288 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "category", - "label": "Noir JS", - "link": { - "type": "doc", - "id": "noir_js/reference/noir_js/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/classes/Noir", - "label": "Noir" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallHandler", - "label": "ForeignCallHandler" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallInput", - "label": "ForeignCallInput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallOutput", - "label": "ForeignCallOutput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ProofData", - "label": "ProofData" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/WitnessMap", - "label": "WitnessMap" - } - ] - }, - { - "type": "category", - "label": "Functions", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/and", - "label": "and" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/blake2s256", - "label": "blake2s256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify", - "label": "ecdsa_secp256k1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify", - "label": "ecdsa_secp256r1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/keccak256", - "label": "keccak256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/sha256", - "label": "sha256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/xor", - "label": "xor" - } - ] - } - ] - }, - { - "type": "category", - "label": "Backend Barretenberg", - "link": { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/classes/BarretenbergBackend", - "label": "BarretenbergBackend" - } - ] - }, - { - "type": "category", - "label": "Interfaces", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/interfaces/Backend", - "label": "Backend" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/BackendOptions", - "label": "BackendOptions" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/ProofData", - "label": "ProofData" - } - ] - } - ] - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.3-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.19.3-sidebars.json deleted file mode 100644 index 6823055c5d3..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.3-sidebars.json +++ /dev/null @@ -1,288 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "category", - "label": "Noir JS", - "link": { - "type": "doc", - "id": "noir_js/reference/noir_js/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/classes/Noir", - "label": "Noir" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallHandler", - "label": "ForeignCallHandler" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallInput", - "label": "ForeignCallInput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallOutput", - "label": "ForeignCallOutput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ProofData", - "label": "ProofData" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/WitnessMap", - "label": "WitnessMap" - } - ] - }, - { - "type": "category", - "label": "Functions", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/and", - "label": "and" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/blake2s256", - "label": "blake2s256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify", - "label": "ecdsa_secp256k1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify", - "label": "ecdsa_secp256r1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/keccak256", - "label": "keccak256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/sha256", - "label": "sha256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/xor", - "label": "xor" - } - ] - } - ] - }, - { - "type": "category", - "label": "Backend Barretenberg", - "link": { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/classes/BarretenbergBackend", - "label": "BarretenbergBackend" - } - ] - }, - { - "type": "category", - "label": "Interfaces", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/interfaces/Backend", - "label": "Backend" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/BackendOptions", - "label": "BackendOptions" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/ProofData", - "label": "ProofData" - } - ] - } - ] - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.4-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.19.4-sidebars.json deleted file mode 100644 index a1675eca18d..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.19.4-sidebars.json +++ /dev/null @@ -1,293 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index", - "label": "Noir" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "Examples", - "items": [ - { - "type": "autogenerated", - "dirName": "examples" - } - ] - }, - { - "type": "category", - "label": "Nargo", - "items": [ - { - "type": "autogenerated", - "dirName": "nargo" - } - ] - }, - { - "type": "category", - "label": "Language Concepts", - "items": [ - { - "type": "category", - "label": "Data Types", - "link": { - "type": "doc", - "id": "language_concepts/data_types" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "language_concepts/data_types" - } - ] - }, - "language_concepts/functions", - "language_concepts/control_flow", - "language_concepts/ops", - "language_concepts/assert", - "language_concepts/unconstrained", - "language_concepts/generics", - "language_concepts/mutability", - "language_concepts/lambdas", - "language_concepts/comments", - "language_concepts/distinct", - "language_concepts/shadowing" - ] - }, - { - "type": "category", - "label": "Noir Standard Library", - "items": [ - { - "type": "category", - "label": "Cryptographic Primitives", - "link": { - "type": "doc", - "id": "standard_library/cryptographic_primitives" - }, - "items": [ - { - "type": "autogenerated", - "dirName": "standard_library/cryptographic_primitives" - } - ] - }, - "standard_library/recursion", - "standard_library/logging", - "standard_library/merkle_trees", - "standard_library/zeroed", - "standard_library/black_box_fns", - "standard_library/options" - ] - }, - { - "type": "category", - "label": "Modules, Packages and Crates", - "items": [ - { - "type": "autogenerated", - "dirName": "modules_packages_crates" - } - ] - }, - { - "type": "category", - "label": "NoirJS", - "link": { - "type": "doc", - "id": "noir_js/noir_js" - }, - "items": [ - { - "type": "category", - "label": "Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "noir_js/getting_started" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "category", - "label": "Noir JS", - "link": { - "type": "doc", - "id": "noir_js/reference/noir_js/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/classes/Noir", - "label": "Noir" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallHandler", - "label": "ForeignCallHandler" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallInput", - "label": "ForeignCallInput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ForeignCallOutput", - "label": "ForeignCallOutput" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/InputMap", - "label": "InputMap" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/ProofData", - "label": "ProofData" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/type-aliases/WitnessMap", - "label": "WitnessMap" - } - ] - }, - { - "type": "category", - "label": "Functions", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/and", - "label": "and" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/blake2s256", - "label": "blake2s256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256k1_verify", - "label": "ecdsa_secp256k1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/ecdsa_secp256r1_verify", - "label": "ecdsa_secp256r1_verify" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/keccak256", - "label": "keccak256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/sha256", - "label": "sha256" - }, - { - "type": "doc", - "id": "noir_js/reference/noir_js/functions/xor", - "label": "xor" - } - ] - } - ] - }, - { - "type": "category", - "label": "Backend Barretenberg", - "link": { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/index" - }, - "items": [ - { - "type": "category", - "label": "Classes", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/classes/BarretenbergBackend", - "label": "BarretenbergBackend" - } - ] - }, - { - "type": "category", - "label": "Interfaces", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/interfaces/Backend", - "label": "Backend" - } - ] - }, - { - "type": "category", - "label": "Type Aliases", - "items": [ - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/BackendOptions", - "label": "BackendOptions" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/CompiledCircuit", - "label": "CompiledCircuit" - }, - { - "type": "doc", - "id": "noir_js/reference/backend_barretenberg/type-aliases/ProofData", - "label": "ProofData" - } - ] - } - ] - } - ] - } - ] - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.22.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.22.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.22.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.23.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.23.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.23.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.24.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.24.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.24.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.25.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.25.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.25.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.26.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.26.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.26.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.27.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.27.0-sidebars.json deleted file mode 100644 index b16f79cc176..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.27.0-sidebars.json +++ /dev/null @@ -1,83 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.28.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.28.0-sidebars.json deleted file mode 100644 index b9ad026f69f..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.28.0-sidebars.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "category", - "label": "Tooling", - "items": [ - { - "type": "autogenerated", - "dirName": "tooling" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.29.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.29.0-sidebars.json deleted file mode 100644 index b9ad026f69f..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.29.0-sidebars.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "category", - "label": "Tooling", - "items": [ - { - "type": "autogenerated", - "dirName": "tooling" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.30.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.30.0-sidebars.json deleted file mode 100644 index b9ad026f69f..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.30.0-sidebars.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "category", - "label": "Tooling", - "items": [ - { - "type": "autogenerated", - "dirName": "tooling" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/docs/versioned_sidebars/version-v0.31.0-sidebars.json b/noir/noir-repo/docs/versioned_sidebars/version-v0.31.0-sidebars.json deleted file mode 100644 index b9ad026f69f..00000000000 --- a/noir/noir-repo/docs/versioned_sidebars/version-v0.31.0-sidebars.json +++ /dev/null @@ -1,93 +0,0 @@ -{ - "sidebar": [ - { - "type": "doc", - "id": "index" - }, - { - "type": "category", - "label": "Getting Started", - "items": [ - { - "type": "autogenerated", - "dirName": "getting_started" - } - ] - }, - { - "type": "category", - "label": "The Noir Language", - "items": [ - { - "type": "autogenerated", - "dirName": "noir" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "category", - "label": "How To Guides", - "items": [ - { - "type": "autogenerated", - "dirName": "how_to" - } - ] - }, - { - "type": "category", - "label": "Explainers", - "items": [ - { - "type": "autogenerated", - "dirName": "explainers" - } - ] - }, - { - "type": "category", - "label": "Tutorials", - "items": [ - { - "type": "autogenerated", - "dirName": "tutorials" - } - ] - }, - { - "type": "category", - "label": "Reference", - "items": [ - { - "type": "autogenerated", - "dirName": "reference" - } - ] - }, - { - "type": "category", - "label": "Tooling", - "items": [ - { - "type": "autogenerated", - "dirName": "tooling" - } - ] - }, - { - "type": "html", - "value": "
", - "defaultStyle": true - }, - { - "type": "doc", - "id": "migration_notes", - "label": "Migration notes" - } - ] -} diff --git a/noir/noir-repo/noir_stdlib/src/embedded_curve_ops.nr b/noir/noir-repo/noir_stdlib/src/embedded_curve_ops.nr index 38bc1764b64..445b6d96554 100644 --- a/noir/noir-repo/noir_stdlib/src/embedded_curve_ops.nr +++ b/noir/noir-repo/noir_stdlib/src/embedded_curve_ops.nr @@ -125,20 +125,63 @@ pub fn fixed_base_scalar_mul(scalar: EmbeddedCurveScalar) -> EmbeddedCurvePoint multi_scalar_mul([g1], [scalar]) } -// This is a hack as returning an `EmbeddedCurvePoint` from a foreign function in brillig returns a [BrilligVariable::SingleAddr; 2] rather than BrilligVariable::BrilligArray +/// This function only assumes that the points are on the curve +/// It handles corner cases around the infinity point causing some overhead compared to embedded_curve_add_not_nul and embedded_curve_add_unsafe +// This is a hack because returning an `EmbeddedCurvePoint` from a foreign function in brillig returns a [BrilligVariable::SingleAddr; 2] rather than BrilligVariable::BrilligArray // as is defined in the brillig bytecode format. This is a workaround which allows us to fix this without modifying the serialization format. // docs:start:embedded_curve_add -fn embedded_curve_add( - point1: EmbeddedCurvePoint, - point2: EmbeddedCurvePoint -) -> EmbeddedCurvePoint -// docs:end:embedded_curve_add -{ - let point_array = embedded_curve_add_array_return(point1, point2); - let x = point_array[0]; - let y = point_array[1]; - EmbeddedCurvePoint { x, y, is_infinite: point_array[2] == 1 } +pub fn embedded_curve_add(point1: EmbeddedCurvePoint, point2: EmbeddedCurvePoint) -> EmbeddedCurvePoint { + // docs:end:embedded_curve_add + let x_coordinates_match = point1.x == point2.x; + let y_coordinates_match = point1.y == point2.y; + let double_predicate = (x_coordinates_match & y_coordinates_match); + let infinity_predicate = (x_coordinates_match & !y_coordinates_match); + let point1_1 = EmbeddedCurvePoint { x: point1.x + (x_coordinates_match as Field), y: point1.y, is_infinite: x_coordinates_match }; + // point1_1 is guaranteed to have a different abscissa than point2 + let mut result = embedded_curve_add_unsafe(point1_1, point2); + result.is_infinite = x_coordinates_match; + + // dbl if x_match, y_match + let double = embedded_curve_add_unsafe(point1, point1); + result = if double_predicate { double } else { result }; + + // infinity if x_match, !y_match + if point1.is_infinite { + result= point2; + } + if point2.is_infinite { + result = point1; + } + let mut result_is_infinity = infinity_predicate & (!point1.is_infinite & !point2.is_infinite); + result.is_infinite = result_is_infinity | (point1.is_infinite & point2.is_infinite); + result } #[foreign(embedded_curve_add)] fn embedded_curve_add_array_return(_point1: EmbeddedCurvePoint, _point2: EmbeddedCurvePoint) -> [Field; 3] {} + +/// This function assumes that: +/// The points are on the curve, and +/// The points don't share an x-coordinate, and +/// Neither point is the infinity point. +/// If it is used with correct input, the function ensures the correct non-zero result is returned. +/// Except for points on the curve, the other assumptions are checked by the function. It will cause assertion failure if they are not respected. +pub fn embedded_curve_add_not_nul(point1: EmbeddedCurvePoint, point2: EmbeddedCurvePoint) -> EmbeddedCurvePoint { + assert(point1.x != point2.x); + assert(!point1.is_infinite); + assert(!point2.is_infinite); + embedded_curve_add_unsafe(point1, point2) +} + +/// Unsafe ec addition +/// If the inputs are the same, it will perform a doubling, but only if point1 and point2 are the same variable. +/// If they have the same value but are different variables, the result will be incorrect because in this case +/// it assumes (but does not check) that the points' x-coordinates are not equal. +/// It also assumes neither point is the infinity point. +pub fn embedded_curve_add_unsafe(point1: EmbeddedCurvePoint, point2: EmbeddedCurvePoint) -> EmbeddedCurvePoint { + let point_array = embedded_curve_add_array_return(point1, point2); + let x = point_array[0]; + let y = point_array[1]; + + EmbeddedCurvePoint { x, y, is_infinite: false } +} diff --git a/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/Nargo.toml b/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/Nargo.toml new file mode 100644 index 00000000000..18d9fc90d9e --- /dev/null +++ b/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/Nargo.toml @@ -0,0 +1,7 @@ +[package] +name = "field_or_int_static_trait_method" +type = "bin" +authors = [""] +compiler_version = ">=0.32.0" + +[dependencies] \ No newline at end of file diff --git a/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/src/main.nr b/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/src/main.nr new file mode 100644 index 00000000000..f5a54c82ce5 --- /dev/null +++ b/noir/noir-repo/test_programs/compile_success_empty/field_or_integer_static_trait_method/src/main.nr @@ -0,0 +1,25 @@ +trait Read { + fn read(data: [Field; 1]) -> Self; +} + +impl Read for Field { + fn read(data: [Field; 1]) -> Self { + data[0] * 10 + } +} + +impl Read for u32 { + fn read(data: [Field; 1]) -> Self { + data[0] as u32 + } +} + +fn main() { + let data = [1]; + + let value: u32 = u32::read(data); + assert_eq(value, 1); + + let value: Field = Field::read(data); + assert_eq(value, 10); +} diff --git a/noir/noir-repo/test_programs/execution_success/verify_honk_proof/Prover.toml b/noir/noir-repo/test_programs/execution_success/verify_honk_proof/Prover.toml index 3f6bf0b427a..debcf3abf86 100644 --- a/noir/noir-repo/test_programs/execution_success/verify_honk_proof/Prover.toml +++ b/noir/noir-repo/test_programs/execution_success/verify_honk_proof/Prover.toml @@ -1,4 +1,575 @@ key_hash = "0x0000000000000000000000000000000000000000000000000000000000000000" -proof = ["0x0000000000000000000000000000000000000000000000000000000000000040", "0x0000000000000000000000000000000000000000000000000000000000000011", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000042ab5d6d1986846cf", "0x00000000000000000000000000000000000000000000000b75c020998797da78", "0x0000000000000000000000000000000000000000000000005a107acb64952eca", "0x000000000000000000000000000000000000000000000000000031e97a575e9d", "0x00000000000000000000000000000000000000000000000b5666547acf8bd5a4", "0x00000000000000000000000000000000000000000000000c410db10a01750aeb", "0x00000000000000000000000000000000000000000000000d722669117f9758a4", "0x000000000000000000000000000000000000000000000000000178cbf4206471", "0x000000000000000000000000000000000000000000000000e91b8a11e7842c38", "0x000000000000000000000000000000000000000000000007fd51009034b3357f", "0x000000000000000000000000000000000000000000000009889939f81e9c7402", "0x0000000000000000000000000000000000000000000000000000f94656a2ca48", "0x000000000000000000000000000000000000000000000006fb128b46c1ddb67f", "0x0000000000000000000000000000000000000000000000093fe27776f50224bd", "0x000000000000000000000000000000000000000000000004a0c80c0da527a081", "0x0000000000000000000000000000000000000000000000000001b52c2020d746", "0x0000000000000000000000000000005a9bae947e1e91af9e4033d8d6aa6ed632", "0x000000000000000000000000000000000025e485e013446d4ac7981c88ba6ecc", "0x000000000000000000000000000000ff1e0496e30ab24a63b32b2d1120b76e62", "0x00000000000000000000000000000000001afe0a8a685d7cd85d1010e55d9d7c", "0x000000000000000000000000000000b0804efd6573805f991458295f510a2004", "0x00000000000000000000000000000000000c81a178016e2fe18605022d5a8b0e", "0x000000000000000000000000000000eba51e76eb1cfff60a53a0092a3c3dea47", "0x000000000000000000000000000000000022e7466247b533282f5936ac4e6c15", "0x00000000000000000000000000000071b1d76edf770edff98f00ff4deec264cd", "0x00000000000000000000000000000000001e48128e68794d8861fcbb2986a383", "0x000000000000000000000000000000d3a2af4915ae6d86b097adc377fafda2d4", "0x000000000000000000000000000000000006359de9ca452dab3a4f1f8d9c9d98", "0x0000000000000000000000000000006cf7dd96d7636fda5953191b1ad776d491", "0x00000000000000000000000000000000001633d881a08d136e834cb13a28fcc6", "0x00000000000000000000000000000001254956cff6908b069fca0e6cf1c47eb1", "0x000000000000000000000000000000000006f4d4dd3890e997e75e75886bf8f7", "0x0000000000000000000000000000006cf7dd96d7636fda5953191b1ad776d491", "0x00000000000000000000000000000000001633d881a08d136e834cb13a28fcc6", "0x00000000000000000000000000000001254956cff6908b069fca0e6cf1c47eb1", "0x000000000000000000000000000000000006f4d4dd3890e997e75e75886bf8f7", "0x000000000000000000000000000000f968b227a358a305607f3efc933823d288", "0x00000000000000000000000000000000000eaf8adb390375a76d95e918b65e08", "0x000000000000000000000000000000bb34b4b447aae56f5e24f81c3acd6d547f", "0x00000000000000000000000000000000002175d012746260ebcfe339a91a81e1", "0x00000000000000000000000000000052eebbd1f6f7554e837f60c44000ed14b6", "0x00000000000000000000000000000000001c1c045a3ec94b8801f2272cc0b3f4", "0x0000000000000000000000000000004d2ef74134578f6b431a9df071ffca4292", "0x0000000000000000000000000000000000291326ade7aa6f0dfc8900eab5580b", "0x0000000000000000000000000000002433eec6418a6dba820c9527e2581fc8bc", "0x00000000000000000000000000000000000e88b7daad19af2ac2f9bdf9e50ee2", "0x000000000000000000000000000000dcfce2c427155cc3e4d035735d3dd5ece8", "0x00000000000000000000000000000000002d7d473cac1a15d0fee8b22c1a7b3e", "0x23fb9503f571d567261006e2ca8b4326d325820140b488bb71617583602f4e3e", "0x0c68b96eebbfcac292403ed3b6f61536550e66473904e7d5d28080108fd0b1c3", "0x08d3bdbefd6d437c50fb9e3e3861913433e76577a18d81aa0ea4b8843e55f9ae", "0x08f6173fe87b72da6d821a496eb99b0cfe0ccadcffd25e5a3b718d83ff9adb1a", "0x1e6bd0a24c2cc58c93cf255cc68dd0c57299c99fd934267906b34facb0145cf4", "0x1175996557630bc376d38636f72b277cb8d54a969a39988a7e78f464c03eaeda", "0x03c3bd1f43baf44de0d9bf0f474c5df04b182214d57a196a717aef8868f9948c", "0x27306ffc7a96c8c27c9812d9dfa649ab6897b69125939aabe814e07d105daa32", "0x0c7f0b70aa08158e55bb39471609782656793ac76a03f2b64dcd135e6542592c", "0x03885b9eff8dac38a64779e3aba31f18c74166892cef9c5081ab57f6daf59865", "0x18dd8385333838c514fd11f36469c88e7ea5f6440aee17fa93c0f03c765d4ced", "0x08ad5bc6c05ecc9ae0d8f0b3196f229a53dbe753f41c12c52045c40e7d8220cc", "0x2f308380f90378084075f2bafa73228b17cbdfc2d693f9aaa1e5089557d0f32e", "0x2d3407e6de05e5935a31037c3db88069d0c41ec86cc8dda815048d6ce76f7a5f", "0x108c231f660e75f209201507a2dba6fccf99734ad91db8ecea675275afdf3ce1", "0x0e68df40e8c467a617229ab0f1dc0d4a04254492e709333d623c0963518dd6b4", "0x290650614292eec7c4f26fd402a047298f1a618dc8ff7de615752f737df7d515", "0x0de290891aaf146fd890a3cd5c25025113df2ec4d0a134513a2f397eaf4e3ea9", "0x25521f6f658bd20d9aaa8041164509b7b8d96fc5ef385f6eb6582375d1a86168", "0x0e9ab2f2f06220644c41fb09456d91751c522b015622f30568e66457f647a2bc", "0x28364f88f1e9c7d8e7767a3b954c5daa29223d646279930b34da51351dc01992", "0x0560c214728aacc262eeee0037be142d81aec26a1f5a9cf0606c4236ed344aa8", "0x1faea1662601fa01ad93d160277a1c81f2c60a761b74660f24a596ec8cb783e7", "0x0e703bb7bbf3a8bb8211715d86a1becb7aa3271f51d6001d5d3042faa7465df9", "0x0cc5b499ea9d9cbae4a0e33a5b601a7f7b686d6980dc0dd5bae4382a8ab1c7c7", "0x27fae143a80a37af95a47d5953096eef9b1127b5475480b8a6ecebdb00a65e23", "0x02cdf7c51d9182fbe07e7768ed0fcfe452ef70fc2ac87dc38fc0d4137bdf4aec", "0x14838df5a54d57d0a28b0375107bb7e7e7259c576a08ea39db6af8b0341d2911", "0x1b1fb0b1242e17beebb218c4ec88c830accea9bc93deec6d087d36d4d8de31fd", "0x1a8c0bdf35e674aa37118f5ad7fe6b62c65d8502e9697b3a92dfda8a1923d110", "0x2819aaa537cf012ceb48a8c8036b6fee492eeeef6698dcf8e3bc825d71efa3f8", "0x1ceedf534535a0d2a427b2ceeb3c8878a658b80eaf5210dbc0d32888fe3d05a7", "0x25c96dba803387eb5f3562785bc3bccddb7c9eb019bd4b07dd4563f77965c00c", "0x0353f3ff0f4f3da362b11eac12167dcbc9b3c76fb555f7e5534c14bb4c3f8037", "0x2904e33424ad29d38bda66a50b54a67acdf09be06a068ddc09d5eabdf9c2a9e5", "0x0b28534bf4b58e7f46c4a7514f3b521dd47bbac2a3adf09387baf19ec8df39c5", "0x1628b67c5d7b8c4cb5d8cdd2d0fd1d92bea3bfcf490fba7f16447cb686d7a388", "0x151bde642447aaf993e737329a3b81c6e243eecbe6a7bb43cdb8ffe74b2c0484", "0x07b319f585e9a9a3883deaddd9b0f43c844cbc7477636034f1543ce9f98821bf", "0x2c8738d76925012cc029f5b888be3cae165daa6beb22b5d73f017c918d891c34", "0x118fff7a26b04a6476c21267a3a4e96247640f6eabd05a05f1a94f881c6ee32b", "0x081d82e0808b6d444b03e1d722375adef2659d5914faa3d9ca4cb12c912be257", "0x18426c5ff5a3140f19bdc05e247cc05e1f70e1ea482b2a2b21f4930a494d7a61", "0x296babb7c6a72783d92bc3dee7f90a97302d64a518faeec0f42af4f599ccc0d1", "0x03337dd83835a2e9fe02c97056360eec725d55b01f039663108939f0333dba11", "0x11a796e7e6f1081be5aad42b475dc224f9547769bc6b358af63207fe0d324a4a", "0x2419618a28070cb7af904460207371f5ff9fa0939f6a0148add60ede530b0f14", "0x004d323457b070f3f41a4ce1ad5a867b3dea1a592bccb40c4d69c8521d9682b6", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x2d6ba30a2a23364900cf52019e2d19574813fe4922763a4e281c58c400ffce14", "0x06a0c085375f88283bedf3a1fc76ef35490655f372e2a985842a9375383b69d7", "0x219b78e5cf2ab2e35edfc8e40362062081a24ff4e9c9d15afa254c2a02d6d4e2", "0x182f29b047e6167c338c36d31685a825c66f327336545c623e7a6bd18e4fa97f", "0x1686460e2586e702724b9daf02315a33ddf5cbd275cfadbc3858f9ef3fe97133", "0x2183aaf585ac708b4000a5b88cf5a767356677087133bd90fff1c3e030b91f1e", "0x27dfa9c69d03c7776fecac8e0f56162caa95f44692cdae91f5b52dfc97eb9006", "0x10a9959de8c6d238c6c6dd68274cc9fc5b6d66759938638072d71659a2fe210d", "0x0e179d6215630fdd7d50362ade21893456d4b9a693e96152d9a6bac6518d4605", "0x0175b579d4e3b24eb0a319a6c79756c8a68ce2c1e0d0d8d1593d685125fbfb66", "0x1132bd3d531944f5024f2705d39b13e00ae90c246f6550c745234fd3d080712b", "0x1f2326f3955b431f2a17e937128b890aa366b107b69c61b8b45832fd06ce9e4e", "0x13576e6c03c3f2042c56113991821ec1f9dec46b6b0ff2748e037c94e6656c40", "0x00bb713034ce9d247110149e2a1754dc76f3ad700d420508148060091037477a", "0x25fb93286a48dc64c67ffac9e3f4a96b6c70bb87744e10e44a782117f8f537a0", "0x191227cd5e49d8a6b5aca93888b3286b41069df547e4bd91ffe65e48ab45b2a8", "0x120d4ac764ca4db67357140c8a8dd1523c013f747250a03a6130416669b087e1", "0x131cc1285b242d73eee36b79ccb3024525ae3caf0f91981cb89ec8d81b16a198", "0x0cacfa5aa1bc4624d5d476aced4d4c8026fb881679172dbc482d18772bc28c9f", "0x0e138279e8a4fe06018e9b9e649921500766e7a7afcc971f41732aa51ec31a43", "0x000000000000000000000000000000332f935a88cd2cc8a138d5ff2efe4cdec8", "0x0e1c2af7515e65c7ebced1a37faf4dbeef5c414f5601219d00d3844658b05a61", "0x12aff8e8eed2d2946c91652d448240590690672893b4759cdd31e1ec9ea45138", "0x1e89f396af25e81f9c4b3af2b0a15fd961789f3a8aa60edbdc4e8f2dfb610375", "0x29c05199f808bf38009ee7fa3c82b6aa5e3d65f180f49d4564c4bf6918399461", "0x019ce7ac46f4e5f1d4ce2d3866321506cea78ff5e5fe400d83b0395341cfe5d5", "0x20b40d1a69e62e7eecbf490915e2791975d3bca30859f237c56c4486e1fbb441", "0x243f7e62233a1f80ee17978814d7ab095bcc416d6bcee4583ce1167c7206b7b4", "0x0b6067a921e8d87bc8fd1af67382fbe2a27bcc833effa13fd7d85b5458d71e28", "0x30307a6766be04f3c50378d1b83f2e147e2ceef344d0c60e1abf939d29c26e27", "0x004c0ec19588b920084d00c6bfe0af4dbf83ca101eac5d833cb8191fe1c298b4", "0x00da79a40286bd8d3993b331a72f8195c7ba04bd863d1afd469bb094e29cc7d9", "0x115b70a2c50ee9abc28472ba8e820cfba158113a5a39c8e31817c84182d0503a", "0x09341d5c4b6d85bde38834a418a8ca375592c320c669bdd540c7ccee760f2ea1", "0x09341d5c4b6d85bde38834a418a8ca375592c320c669bdd540c7ccee760f2ea1", "0x0e63e927a9562ce0914fcd8892dff9a94ac722365ce21b8f5c75cc560b364e57", "0x05cf84989894e741a3e1cd815a8f84febfb08e61ee7b424c902fb02ca7d12e95", "0x1f958ad88d5e4a270f35e534154e7a519c5bbfab36d5084202d5b78baf63e09e", "0x21f0a33450db8821c2f8d042aae7e70bf05c9814b063e73c5e95f8ddba515a81", "0x2767a30fa0351c7deb2c8f542ecace4c41c1d136dd460dfad50b372f2a5f4b71", "0x137ee4ebfbc7227bf57ffc35d3368dd4f96c62911db9380aafa220d061c3b59d", "0x111515d3566611192f64e1e0848635ca6d7f73d8039d8b3522da1e2359e6d1b2", "0x2f6284e905c491b8defe4c467b2e664e2fbf144b5ca45e05c4a9d1aa8d41e149", "0x1e688ca09721459cd96d6af042716567a8f5fdb479f08ff9eff248c6013315a4", "0x00000000000000000000000000000015207c89ecabf752a46c0d5b8dbd296d86", "0x0000000000000000000000000000000000286c2b4d49249737816da8fd9f2753", "0x0000000000000000000000000000002492e649af820ca5d83e59823126c03bfb", "0x00000000000000000000000000000000001cdf1b636e33bf02a813687147476e", "0x000000000000000000000000000000b49023689f96212b8166d0c9b105e6df9a", "0x00000000000000000000000000000000000d9d27730e57d86079464ecd8d9edd", "0x0000000000000000000000000000005292b5583bd716a723bae47d344d655528", "0x000000000000000000000000000000000026651dba1a1074382c734163ab3614", "0x0000000000000000000000000000008984f01bc1f237c72fd6d2bb10cc21eb85", "0x00000000000000000000000000000000001029818de60ae9bb21ac2b5d5a4c97", "0x0000000000000000000000000000003aca28da52679f34e33756dfe00f1d8072", "0x0000000000000000000000000000000000124ecac53af720c02d18f54fd29100", "0x000000000000000000000000000000d09ed1c104d0397f046d89b8476f47e641", "0x00000000000000000000000000000000002c5094b27ad41c8a203b16dc74ee54", "0x000000000000000000000000000000bf8609068d29793771eb3f64e7dc3db96d", "0x0000000000000000000000000000000000225e220e16aedaecf2c10de6e41042", "0x0000000000000000000000000000006ae4f0d8baca7866ad4632141f90770cd7", "0x0000000000000000000000000000000000256cb979ab5bbe98be3a413ae8f246", "0x000000000000000000000000000000891f30bd3ac8e7e63e00db4951d518822f", "0x000000000000000000000000000000000014dffca5d842acfcd23fa491a7dae2", "0x000000000000000000000000000000af99905ea5b7a25f2172f044a59b90e67d", "0x00000000000000000000000000000000001e35bb78e382a5b98ad04b846df528", "0x0000000000000000000000000000003cfb75469b791ea188b8dfdff0f269e7b5", "0x00000000000000000000000000000000000e4fb9eb44a3d44d808794066f8811", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x000000000000000000000000000000c42f38f2993af03e18e76996c49f945c6a", "0x00000000000000000000000000000000002aefe820f0e4700abedd9fb6f046c1", "0x0000000000000000000000000000007a878e53414bf22854877c5066eaf916b8", "0x00000000000000000000000000000000001410a75247434da28c1ba6b64703bb", "0x000000000000000000000000000000bca902c1e2af8b47771e7eb42c3870f46b", "0x0000000000000000000000000000000000276eb602c3c232b51668d229d602b8", "0x000000000000000000000000000000dac1254c0753ee39d49d795bc6b3550ba7", "0x000000000000000000000000000000000007d60be9174146bd83f202aa062b92"] -public_inputs = ["0x0000000000000000000000000000000000000000000000000000000000000003"] -verification_key = ["0x0000000000000000000000000000000000000000000000000000000000000040", "0x0000000000000000000000000000000000000000000000000000000000000011", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000003", "0x0000000000000000000000000000000000000000000000000000000000000004", "0x0000000000000000000000000000000000000000000000000000000000000005", "0x0000000000000000000000000000000000000000000000000000000000000006", "0x0000000000000000000000000000000000000000000000000000000000000007", "0x0000000000000000000000000000000000000000000000000000000000000008", "0x0000000000000000000000000000000000000000000000000000000000000009", "0x000000000000000000000000000000000000000000000000000000000000000a", "0x000000000000000000000000000000000000000000000000000000000000000b", "0x000000000000000000000000000000000000000000000000000000000000000c", "0x000000000000000000000000000000000000000000000000000000000000000d", "0x000000000000000000000000000000000000000000000000000000000000000e", "0x000000000000000000000000000000000000000000000000000000000000000f", "0x0000000000000000000000000000000000000000000000000000000000000010", "0x00000000000000000000000000000060e430ad1c23bfcf3514323aae3f206e84", "0x00000000000000000000000000000000001b5c3ff4c2458d8f481b1c068f27ae", "0x000000000000000000000000000000bb510ab2112def34980e4fc6998ad9dd16", "0x00000000000000000000000000000000000576e7c105b43e061e13cb877fefe1", "0x000000000000000000000000000000ced074785d11857b065d8199e6669a601c", "0x00000000000000000000000000000000000053b48a4098c1c0ae268f273952f7", "0x000000000000000000000000000000d1d4b26e941db8168cee8f6de548ae0fd8", "0x00000000000000000000000000000000001a9adf5a6dadc3d948bb61dfd63f4c", "0x0000000000000000000000000000009ce1faac6f8de6ebb18f1db17372c82ad5", "0x00000000000000000000000000000000002002681bb417184b2df070a16a3858", "0x000000000000000000000000000000161baa651a8092e0e84725594de5aba511", "0x00000000000000000000000000000000000be0064399c2a1efff9eb0cdcb2223", "0x0000000000000000000000000000008673be6fd1bdbe980a29d8c1ded54381e7", "0x000000000000000000000000000000000008a5158a7d9648cf1d234524c9fa0c", "0x0000000000000000000000000000002b4fce6e4b1c72062b296d49bca2aa4130", "0x00000000000000000000000000000000002e45a9eff4b6769e55fb710cded44f", "0x00000000000000000000000000000072b85bf733758b76bcf97333efb85a23e3", "0x000000000000000000000000000000000017da0ea508994fc82862715e4b5592", "0x00000000000000000000000000000094fa74695cf058dba8ff35aec95456c6c3", "0x0000000000000000000000000000000000211acddb851061c24b8f159e832bd1", "0x000000000000000000000000000000303b5e5c531384b9a792e11702ad3bcab0", "0x00000000000000000000000000000000000d336dff51a60b8833d5d7f6d4314c", "0x0000000000000000000000000000009f825dde88092070747180d581c342444a", "0x0000000000000000000000000000000000237fbd6511a03cca8cac01b555fe01", "0x0000000000000000000000000000007c313205159495df6d8de292079a4844ff", "0x000000000000000000000000000000000018facdfc468530dd45e8f7a1d38ce9", "0x0000000000000000000000000000000d1ce33446fc3dc4ab40ca38d92dac74e1", "0x00000000000000000000000000000000000852d8e3e0e8f4435af3e94222688b", "0x0000000000000000000000000000006c04ee19ec1dfec87ed47d6d04aa158de2", "0x000000000000000000000000000000000013240f97a584b45184c8ec31319b5f", "0x000000000000000000000000000000cefb5d240b07ceb4be26ea429b6dc9d9e0", "0x00000000000000000000000000000000002dad22022121d689f57fb38ca21349", "0x000000000000000000000000000000c9f189f2a91aeb664ce376d8b157ba98f8", "0x00000000000000000000000000000000002531a51ad54f124d58094b219818d2", "0x000000000000000000000000000000ef1e6db71809307f677677e62b4163f556", "0x0000000000000000000000000000000000272da4396fb2a7ee0638b9140e523d", "0x0000000000000000000000000000002e54c0244a7732c87bc4712a76dd8c83fb", "0x000000000000000000000000000000000007db77b3e04b7eba9643da57cbbe4d", "0x000000000000000000000000000000e0dfe1ddd7f74ae0d636c910c3e85830d8", "0x00000000000000000000000000000000000466fa9b57ec4664abd1505b490862", "0x0000000000000000000000000000009ee55ae8a32fe5384c79907067cc27192e", "0x00000000000000000000000000000000000799d0e465cec07ecb5238c854e830", "0x0000000000000000000000000000001d5910ad361e76e1c241247a823733c39f", "0x00000000000000000000000000000000002b03f2ccf7507564da2e6678bef8fe", "0x000000000000000000000000000000ee40d90bea71fba7a412dd61fcf34e8ceb", "0x0000000000000000000000000000000000140b0936c323fd2471155617b6af56", "0x0000000000000000000000000000002b90071823185c5ff8e440fd3d73b6fefc", "0x00000000000000000000000000000000002b6c10790a5f6631c87d652e059df4", "0x00000000000000000000000000000029a17181c7934fc3fdbd352eac5cb521b9", "0x00000000000000000000000000000000001f497cbf5284ff29a2d336e5991999", "0x000000000000000000000000000000072bd9c0c6beda1fdee6d4ff0432ba9e1b", "0x000000000000000000000000000000000013ea38a0bd2aa751a490a724fac818", "0x000000000000000000000000000000c599f63dcd3edd49f08ae5c3141c1e3493", "0x00000000000000000000000000000000002bdb36be0bea09950dd32a8ccf6fbc", "0x00000000000000000000000000000047f27f29724e7f19eba0340256a0bd4b7d", "0x00000000000000000000000000000000001c1c5ccf87a962129ca785f8f35120", "0x000000000000000000000000000000c5c71efdae00679bbe4a95096e012b1817", "0x000000000000000000000000000000000017a365de041e317817d0135f2b48e0", "0x0000000000000000000000000000008ae711ac402f7848d719c93a89ba8d39f1", "0x00000000000000000000000000000000002b6fb40ed8a1935226f4f9786a0499", "0x0000000000000000000000000000002f03a71501d83de1da5715a4e9462d6198", "0x00000000000000000000000000000000001644064443b8546f48eae693af47b8", "0x00000000000000000000000000000083763ab1b6e8fe269b2fe4c7b9c448c08d", "0x000000000000000000000000000000000021d7cc18c59676a8eeb47c0111c251", "0x000000000000000000000000000000b5f937153073e03ea7d51a996e0ebc2e6b", "0x000000000000000000000000000000000011ddd0e26457373eb06e0493177672", "0x000000000000000000000000000000c5f6eb9f6fc8fa99811a4a88c74a6d018b", "0x000000000000000000000000000000000025bcd07a0732c123567834f5109558", "0x000000000000000000000000000000aeb08a0b1a4442189448b4e97490568146", "0x000000000000000000000000000000000002a1744e4771705536a88f07e0f90f", "0x000000000000000000000000000000b938568293bd0724b0ea76c2ec34c4a829", "0x0000000000000000000000000000000000053296e8f3b9ad3af877dfa9c7c2a7", "0x000000000000000000000000000000f0ca1db6323996eba26bdc86dafef9d10b", "0x00000000000000000000000000000000001441a46c58af03d5645d52721d956a", "0x0000000000000000000000000000008bbf8f884013c66c28ba09c2fbd573b656", "0x0000000000000000000000000000000000206c391ca06fac27d1908e94570243", "0x0000000000000000000000000000002d4f5aaed88ba4f79612d53b804ca8f194", "0x00000000000000000000000000000000001674011c96392df08970fa6b7b4cb8", "0x0000000000000000000000000000009f88297c1729d76c4d9306853598c91325", "0x0000000000000000000000000000000000256f51adfcacc3c1e340be4d32d3e9", "0x0000000000000000000000000000000ab9955eec0d74eb799afed2a802b24d75", "0x00000000000000000000000000000000001fcbe43ea105b30d36ed0b21b03411", "0x000000000000000000000000000000d66b1d5433f1aa5305cd1edce7c22de466", "0x00000000000000000000000000000000002331546a256b8a3b751956806680d4", "0x000000000000000000000000000000e97954ad6cd6f45fb15c91434121db4304", "0x00000000000000000000000000000000002e20a97e09d50f227ced47e7a98250", "0x0000000000000000000000000000001ebbc27eb9ebededefba79522eb58ae89b", "0x0000000000000000000000000000000000090efa4974e566e81d1177b85a30be", "0x0000000000000000000000000000005eafa070b9c9632404052642e3bc14f9fd", "0x00000000000000000000000000000000001489068864102daca6a6b8bc4d448b", "0x0000000000000000000000000000009ebc91aaaac036a6477cadbe54e8556dfd", "0x00000000000000000000000000000000000ef6d835e2ed3343b95c82c8c54037", "0x00000000000000000000000000000033b28b529dff46e93af4e7422530478e4a", "0x000000000000000000000000000000000020a86c2f8591bf190bcddcc03c42fb", "0x000000000000000000000000000000a9679d0acc088f7dc27bf6d866bcd2dda2", "0x00000000000000000000000000000000002fb9d0d2d4099402bed74f738f64cc", "0x00000000000000000000000000000023b09f876a29a061582848a8b9a5870c12", "0x00000000000000000000000000000000001d5bb906f03f0d49e9c4791bc43af9", "0x00000000000000000000000000000017aac9854ea240d8ec97bf760c4d4ba870", "0x00000000000000000000000000000000000b227a556c414ada0dc75bb303e30e", "0x0000000000000000000000000000000000000000000000000000000000000001", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000000000000000000000000000000000000002", "0x0000000000000000000000000000000000000000000000000000000000000000", "0x0000000000000000000000000000009b624fa65d1a24b7f14a8f25f3789622af", "0x000000000000000000000000000000000013d47bff8c630e847b70e2732fd3f0", "0x00000000000000000000000000000061d21663e93132f32921075f4c936a84df", "0x00000000000000000000000000000000001a74ca4e118fb480b9b999902989a3"] +proof = [ + "0x0000000000000000000000000000000000000000000000000000000000000040", + "0x0000000000000000000000000000000000000000000000000000000000000011", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000042ab5d6d1986846cf", + "0x00000000000000000000000000000000000000000000000b75c020998797da78", + "0x0000000000000000000000000000000000000000000000005a107acb64952eca", + "0x000000000000000000000000000000000000000000000000000031e97a575e9d", + "0x00000000000000000000000000000000000000000000000b5666547acf8bd5a4", + "0x00000000000000000000000000000000000000000000000c410db10a01750aeb", + "0x00000000000000000000000000000000000000000000000d722669117f9758a4", + "0x000000000000000000000000000000000000000000000000000178cbf4206471", + "0x000000000000000000000000000000000000000000000000e91b8a11e7842c38", + "0x000000000000000000000000000000000000000000000007fd51009034b3357f", + "0x000000000000000000000000000000000000000000000009889939f81e9c7402", + "0x0000000000000000000000000000000000000000000000000000f94656a2ca48", + "0x000000000000000000000000000000000000000000000006fb128b46c1ddb67f", + "0x0000000000000000000000000000000000000000000000093fe27776f50224bd", + "0x000000000000000000000000000000000000000000000004a0c80c0da527a081", + "0x0000000000000000000000000000000000000000000000000001b52c2020d746", + "0x0000000000000000000000000000005a9bae947e1e91af9e4033d8d6aa6ed632", + "0x000000000000000000000000000000000025e485e013446d4ac7981c88ba6ecc", + "0x000000000000000000000000000000ff1e0496e30ab24a63b32b2d1120b76e62", + "0x00000000000000000000000000000000001afe0a8a685d7cd85d1010e55d9d7c", + "0x000000000000000000000000000000b0804efd6573805f991458295f510a2004", + "0x00000000000000000000000000000000000c81a178016e2fe18605022d5a8b0e", + "0x000000000000000000000000000000eba51e76eb1cfff60a53a0092a3c3dea47", + "0x000000000000000000000000000000000022e7466247b533282f5936ac4e6c15", + "0x00000000000000000000000000000071b1d76edf770edff98f00ff4deec264cd", + "0x00000000000000000000000000000000001e48128e68794d8861fcbb2986a383", + "0x000000000000000000000000000000d3a2af4915ae6d86b097adc377fafda2d4", + "0x000000000000000000000000000000000006359de9ca452dab3a4f1f8d9c9d98", + "0x0000000000000000000000000000006cf7dd96d7636fda5953191b1ad776d491", + "0x00000000000000000000000000000000001633d881a08d136e834cb13a28fcc6", + "0x00000000000000000000000000000001254956cff6908b069fca0e6cf1c47eb1", + "0x000000000000000000000000000000000006f4d4dd3890e997e75e75886bf8f7", + "0x0000000000000000000000000000006cf7dd96d7636fda5953191b1ad776d491", + "0x00000000000000000000000000000000001633d881a08d136e834cb13a28fcc6", + "0x00000000000000000000000000000001254956cff6908b069fca0e6cf1c47eb1", + "0x000000000000000000000000000000000006f4d4dd3890e997e75e75886bf8f7", + "0x000000000000000000000000000000f968b227a358a305607f3efc933823d288", + "0x00000000000000000000000000000000000eaf8adb390375a76d95e918b65e08", + "0x000000000000000000000000000000bb34b4b447aae56f5e24f81c3acd6d547f", + "0x00000000000000000000000000000000002175d012746260ebcfe339a91a81e1", + "0x00000000000000000000000000000052eebbd1f6f7554e837f60c44000ed14b6", + "0x00000000000000000000000000000000001c1c045a3ec94b8801f2272cc0b3f4", + "0x0000000000000000000000000000004d2ef74134578f6b431a9df071ffca4292", + "0x0000000000000000000000000000000000291326ade7aa6f0dfc8900eab5580b", + "0x0000000000000000000000000000002433eec6418a6dba820c9527e2581fc8bc", + "0x00000000000000000000000000000000000e88b7daad19af2ac2f9bdf9e50ee2", + "0x000000000000000000000000000000dcfce2c427155cc3e4d035735d3dd5ece8", + "0x00000000000000000000000000000000002d7d473cac1a15d0fee8b22c1a7b3e", + "0x23fb9503f571d567261006e2ca8b4326d325820140b488bb71617583602f4e3e", + "0x0c68b96eebbfcac292403ed3b6f61536550e66473904e7d5d28080108fd0b1c3", + "0x08d3bdbefd6d437c50fb9e3e3861913433e76577a18d81aa0ea4b8843e55f9ae", + "0x08f6173fe87b72da6d821a496eb99b0cfe0ccadcffd25e5a3b718d83ff9adb1a", + "0x1e6bd0a24c2cc58c93cf255cc68dd0c57299c99fd934267906b34facb0145cf4", + "0x1175996557630bc376d38636f72b277cb8d54a969a39988a7e78f464c03eaeda", + "0x03c3bd1f43baf44de0d9bf0f474c5df04b182214d57a196a717aef8868f9948c", + "0x27306ffc7a96c8c27c9812d9dfa649ab6897b69125939aabe814e07d105daa32", + "0x0c7f0b70aa08158e55bb39471609782656793ac76a03f2b64dcd135e6542592c", + "0x03885b9eff8dac38a64779e3aba31f18c74166892cef9c5081ab57f6daf59865", + "0x18dd8385333838c514fd11f36469c88e7ea5f6440aee17fa93c0f03c765d4ced", + "0x08ad5bc6c05ecc9ae0d8f0b3196f229a53dbe753f41c12c52045c40e7d8220cc", + "0x2f308380f90378084075f2bafa73228b17cbdfc2d693f9aaa1e5089557d0f32e", + "0x2d3407e6de05e5935a31037c3db88069d0c41ec86cc8dda815048d6ce76f7a5f", + "0x108c231f660e75f209201507a2dba6fccf99734ad91db8ecea675275afdf3ce1", + "0x0e68df40e8c467a617229ab0f1dc0d4a04254492e709333d623c0963518dd6b4", + "0x290650614292eec7c4f26fd402a047298f1a618dc8ff7de615752f737df7d515", + "0x0de290891aaf146fd890a3cd5c25025113df2ec4d0a134513a2f397eaf4e3ea9", + "0x25521f6f658bd20d9aaa8041164509b7b8d96fc5ef385f6eb6582375d1a86168", + "0x0e9ab2f2f06220644c41fb09456d91751c522b015622f30568e66457f647a2bc", + "0x28364f88f1e9c7d8e7767a3b954c5daa29223d646279930b34da51351dc01992", + "0x0560c214728aacc262eeee0037be142d81aec26a1f5a9cf0606c4236ed344aa8", + "0x1faea1662601fa01ad93d160277a1c81f2c60a761b74660f24a596ec8cb783e7", + "0x0e703bb7bbf3a8bb8211715d86a1becb7aa3271f51d6001d5d3042faa7465df9", + "0x0cc5b499ea9d9cbae4a0e33a5b601a7f7b686d6980dc0dd5bae4382a8ab1c7c7", + "0x27fae143a80a37af95a47d5953096eef9b1127b5475480b8a6ecebdb00a65e23", + "0x02cdf7c51d9182fbe07e7768ed0fcfe452ef70fc2ac87dc38fc0d4137bdf4aec", + "0x14838df5a54d57d0a28b0375107bb7e7e7259c576a08ea39db6af8b0341d2911", + "0x1b1fb0b1242e17beebb218c4ec88c830accea9bc93deec6d087d36d4d8de31fd", + "0x1a8c0bdf35e674aa37118f5ad7fe6b62c65d8502e9697b3a92dfda8a1923d110", + "0x2819aaa537cf012ceb48a8c8036b6fee492eeeef6698dcf8e3bc825d71efa3f8", + "0x1ceedf534535a0d2a427b2ceeb3c8878a658b80eaf5210dbc0d32888fe3d05a7", + "0x25c96dba803387eb5f3562785bc3bccddb7c9eb019bd4b07dd4563f77965c00c", + "0x0353f3ff0f4f3da362b11eac12167dcbc9b3c76fb555f7e5534c14bb4c3f8037", + "0x2904e33424ad29d38bda66a50b54a67acdf09be06a068ddc09d5eabdf9c2a9e5", + "0x0b28534bf4b58e7f46c4a7514f3b521dd47bbac2a3adf09387baf19ec8df39c5", + "0x1628b67c5d7b8c4cb5d8cdd2d0fd1d92bea3bfcf490fba7f16447cb686d7a388", + "0x151bde642447aaf993e737329a3b81c6e243eecbe6a7bb43cdb8ffe74b2c0484", + "0x07b319f585e9a9a3883deaddd9b0f43c844cbc7477636034f1543ce9f98821bf", + "0x2c8738d76925012cc029f5b888be3cae165daa6beb22b5d73f017c918d891c34", + "0x118fff7a26b04a6476c21267a3a4e96247640f6eabd05a05f1a94f881c6ee32b", + "0x081d82e0808b6d444b03e1d722375adef2659d5914faa3d9ca4cb12c912be257", + "0x18426c5ff5a3140f19bdc05e247cc05e1f70e1ea482b2a2b21f4930a494d7a61", + "0x296babb7c6a72783d92bc3dee7f90a97302d64a518faeec0f42af4f599ccc0d1", + "0x03337dd83835a2e9fe02c97056360eec725d55b01f039663108939f0333dba11", + "0x11a796e7e6f1081be5aad42b475dc224f9547769bc6b358af63207fe0d324a4a", + "0x2419618a28070cb7af904460207371f5ff9fa0939f6a0148add60ede530b0f14", + "0x004d323457b070f3f41a4ce1ad5a867b3dea1a592bccb40c4d69c8521d9682b6", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x2d6ba30a2a23364900cf52019e2d19574813fe4922763a4e281c58c400ffce14", + "0x06a0c085375f88283bedf3a1fc76ef35490655f372e2a985842a9375383b69d7", + "0x219b78e5cf2ab2e35edfc8e40362062081a24ff4e9c9d15afa254c2a02d6d4e2", + "0x182f29b047e6167c338c36d31685a825c66f327336545c623e7a6bd18e4fa97f", + "0x1686460e2586e702724b9daf02315a33ddf5cbd275cfadbc3858f9ef3fe97133", + "0x2183aaf585ac708b4000a5b88cf5a767356677087133bd90fff1c3e030b91f1e", + "0x27dfa9c69d03c7776fecac8e0f56162caa95f44692cdae91f5b52dfc97eb9006", + "0x10a9959de8c6d238c6c6dd68274cc9fc5b6d66759938638072d71659a2fe210d", + "0x0e179d6215630fdd7d50362ade21893456d4b9a693e96152d9a6bac6518d4605", + "0x0175b579d4e3b24eb0a319a6c79756c8a68ce2c1e0d0d8d1593d685125fbfb66", + "0x1132bd3d531944f5024f2705d39b13e00ae90c246f6550c745234fd3d080712b", + "0x1f2326f3955b431f2a17e937128b890aa366b107b69c61b8b45832fd06ce9e4e", + "0x13576e6c03c3f2042c56113991821ec1f9dec46b6b0ff2748e037c94e6656c40", + "0x00bb713034ce9d247110149e2a1754dc76f3ad700d420508148060091037477a", + "0x25fb93286a48dc64c67ffac9e3f4a96b6c70bb87744e10e44a782117f8f537a0", + "0x191227cd5e49d8a6b5aca93888b3286b41069df547e4bd91ffe65e48ab45b2a8", + "0x120d4ac764ca4db67357140c8a8dd1523c013f747250a03a6130416669b087e1", + "0x131cc1285b242d73eee36b79ccb3024525ae3caf0f91981cb89ec8d81b16a198", + "0x0cacfa5aa1bc4624d5d476aced4d4c8026fb881679172dbc482d18772bc28c9f", + "0x0e138279e8a4fe06018e9b9e649921500766e7a7afcc971f41732aa51ec31a43", + "0x000000000000000000000000000000332f935a88cd2cc8a138d5ff2efe4cdec8", + "0x0e1c2af7515e65c7ebced1a37faf4dbeef5c414f5601219d00d3844658b05a61", + "0x12aff8e8eed2d2946c91652d448240590690672893b4759cdd31e1ec9ea45138", + "0x1e89f396af25e81f9c4b3af2b0a15fd961789f3a8aa60edbdc4e8f2dfb610375", + "0x29c05199f808bf38009ee7fa3c82b6aa5e3d65f180f49d4564c4bf6918399461", + "0x019ce7ac46f4e5f1d4ce2d3866321506cea78ff5e5fe400d83b0395341cfe5d5", + "0x20b40d1a69e62e7eecbf490915e2791975d3bca30859f237c56c4486e1fbb441", + "0x243f7e62233a1f80ee17978814d7ab095bcc416d6bcee4583ce1167c7206b7b4", + "0x0b6067a921e8d87bc8fd1af67382fbe2a27bcc833effa13fd7d85b5458d71e28", + "0x30307a6766be04f3c50378d1b83f2e147e2ceef344d0c60e1abf939d29c26e27", + "0x004c0ec19588b920084d00c6bfe0af4dbf83ca101eac5d833cb8191fe1c298b4", + "0x00da79a40286bd8d3993b331a72f8195c7ba04bd863d1afd469bb094e29cc7d9", + "0x115b70a2c50ee9abc28472ba8e820cfba158113a5a39c8e31817c84182d0503a", + "0x09341d5c4b6d85bde38834a418a8ca375592c320c669bdd540c7ccee760f2ea1", + "0x09341d5c4b6d85bde38834a418a8ca375592c320c669bdd540c7ccee760f2ea1", + "0x0e63e927a9562ce0914fcd8892dff9a94ac722365ce21b8f5c75cc560b364e57", + "0x05cf84989894e741a3e1cd815a8f84febfb08e61ee7b424c902fb02ca7d12e95", + "0x1f958ad88d5e4a270f35e534154e7a519c5bbfab36d5084202d5b78baf63e09e", + "0x21f0a33450db8821c2f8d042aae7e70bf05c9814b063e73c5e95f8ddba515a81", + "0x2767a30fa0351c7deb2c8f542ecace4c41c1d136dd460dfad50b372f2a5f4b71", + "0x137ee4ebfbc7227bf57ffc35d3368dd4f96c62911db9380aafa220d061c3b59d", + "0x111515d3566611192f64e1e0848635ca6d7f73d8039d8b3522da1e2359e6d1b2", + "0x2f6284e905c491b8defe4c467b2e664e2fbf144b5ca45e05c4a9d1aa8d41e149", + "0x1e688ca09721459cd96d6af042716567a8f5fdb479f08ff9eff248c6013315a4", + "0x00000000000000000000000000000015207c89ecabf752a46c0d5b8dbd296d86", + "0x0000000000000000000000000000000000286c2b4d49249737816da8fd9f2753", + "0x0000000000000000000000000000002492e649af820ca5d83e59823126c03bfb", + "0x00000000000000000000000000000000001cdf1b636e33bf02a813687147476e", + "0x000000000000000000000000000000b49023689f96212b8166d0c9b105e6df9a", + "0x00000000000000000000000000000000000d9d27730e57d86079464ecd8d9edd", + "0x0000000000000000000000000000005292b5583bd716a723bae47d344d655528", + "0x000000000000000000000000000000000026651dba1a1074382c734163ab3614", + "0x0000000000000000000000000000008984f01bc1f237c72fd6d2bb10cc21eb85", + "0x00000000000000000000000000000000001029818de60ae9bb21ac2b5d5a4c97", + "0x0000000000000000000000000000003aca28da52679f34e33756dfe00f1d8072", + "0x0000000000000000000000000000000000124ecac53af720c02d18f54fd29100", + "0x000000000000000000000000000000d09ed1c104d0397f046d89b8476f47e641", + "0x00000000000000000000000000000000002c5094b27ad41c8a203b16dc74ee54", + "0x000000000000000000000000000000bf8609068d29793771eb3f64e7dc3db96d", + "0x0000000000000000000000000000000000225e220e16aedaecf2c10de6e41042", + "0x0000000000000000000000000000006ae4f0d8baca7866ad4632141f90770cd7", + "0x0000000000000000000000000000000000256cb979ab5bbe98be3a413ae8f246", + "0x000000000000000000000000000000891f30bd3ac8e7e63e00db4951d518822f", + "0x000000000000000000000000000000000014dffca5d842acfcd23fa491a7dae2", + "0x000000000000000000000000000000af99905ea5b7a25f2172f044a59b90e67d", + "0x00000000000000000000000000000000001e35bb78e382a5b98ad04b846df528", + "0x0000000000000000000000000000003cfb75469b791ea188b8dfdff0f269e7b5", + "0x00000000000000000000000000000000000e4fb9eb44a3d44d808794066f8811", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x000000000000000000000000000000c42f38f2993af03e18e76996c49f945c6a", + "0x00000000000000000000000000000000002aefe820f0e4700abedd9fb6f046c1", + "0x0000000000000000000000000000007a878e53414bf22854877c5066eaf916b8", + "0x00000000000000000000000000000000001410a75247434da28c1ba6b64703bb", + "0x000000000000000000000000000000bca902c1e2af8b47771e7eb42c3870f46b", + "0x0000000000000000000000000000000000276eb602c3c232b51668d229d602b8", + "0x000000000000000000000000000000dac1254c0753ee39d49d795bc6b3550ba7", + "0x000000000000000000000000000000000007d60be9174146bd83f202aa062b92", +] +public_inputs = [ + "0x0000000000000000000000000000000000000000000000000000000000000003", +] +verification_key = [ + "0x0000000000000000000000000000000000000000000000000000000000000040", + "0x0000000000000000000000000000000000000000000000000000000000000011", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000003", + "0x0000000000000000000000000000000000000000000000000000000000000004", + "0x0000000000000000000000000000000000000000000000000000000000000005", + "0x0000000000000000000000000000000000000000000000000000000000000006", + "0x0000000000000000000000000000000000000000000000000000000000000007", + "0x0000000000000000000000000000000000000000000000000000000000000008", + "0x0000000000000000000000000000000000000000000000000000000000000009", + "0x000000000000000000000000000000000000000000000000000000000000000a", + "0x000000000000000000000000000000000000000000000000000000000000000b", + "0x000000000000000000000000000000000000000000000000000000000000000c", + "0x000000000000000000000000000000000000000000000000000000000000000d", + "0x000000000000000000000000000000000000000000000000000000000000000e", + "0x000000000000000000000000000000000000000000000000000000000000000f", + "0x0000000000000000000000000000000000000000000000000000000000000010", + "0x00000000000000000000000000000060e430ad1c23bfcf3514323aae3f206e84", + "0x00000000000000000000000000000000001b5c3ff4c2458d8f481b1c068f27ae", + "0x000000000000000000000000000000bb510ab2112def34980e4fc6998ad9dd16", + "0x00000000000000000000000000000000000576e7c105b43e061e13cb877fefe1", + "0x000000000000000000000000000000ced074785d11857b065d8199e6669a601c", + "0x00000000000000000000000000000000000053b48a4098c1c0ae268f273952f7", + "0x000000000000000000000000000000d1d4b26e941db8168cee8f6de548ae0fd8", + "0x00000000000000000000000000000000001a9adf5a6dadc3d948bb61dfd63f4c", + "0x0000000000000000000000000000009ce1faac6f8de6ebb18f1db17372c82ad5", + "0x00000000000000000000000000000000002002681bb417184b2df070a16a3858", + "0x000000000000000000000000000000161baa651a8092e0e84725594de5aba511", + "0x00000000000000000000000000000000000be0064399c2a1efff9eb0cdcb2223", + "0x0000000000000000000000000000008673be6fd1bdbe980a29d8c1ded54381e7", + "0x000000000000000000000000000000000008a5158a7d9648cf1d234524c9fa0c", + "0x0000000000000000000000000000002b4fce6e4b1c72062b296d49bca2aa4130", + "0x00000000000000000000000000000000002e45a9eff4b6769e55fb710cded44f", + "0x00000000000000000000000000000072b85bf733758b76bcf97333efb85a23e3", + "0x000000000000000000000000000000000017da0ea508994fc82862715e4b5592", + "0x00000000000000000000000000000094fa74695cf058dba8ff35aec95456c6c3", + "0x0000000000000000000000000000000000211acddb851061c24b8f159e832bd1", + "0x000000000000000000000000000000303b5e5c531384b9a792e11702ad3bcab0", + "0x00000000000000000000000000000000000d336dff51a60b8833d5d7f6d4314c", + "0x0000000000000000000000000000009f825dde88092070747180d581c342444a", + "0x0000000000000000000000000000000000237fbd6511a03cca8cac01b555fe01", + "0x0000000000000000000000000000007c313205159495df6d8de292079a4844ff", + "0x000000000000000000000000000000000018facdfc468530dd45e8f7a1d38ce9", + "0x0000000000000000000000000000000d1ce33446fc3dc4ab40ca38d92dac74e1", + "0x00000000000000000000000000000000000852d8e3e0e8f4435af3e94222688b", + "0x0000000000000000000000000000006c04ee19ec1dfec87ed47d6d04aa158de2", + "0x000000000000000000000000000000000013240f97a584b45184c8ec31319b5f", + "0x000000000000000000000000000000cefb5d240b07ceb4be26ea429b6dc9d9e0", + "0x00000000000000000000000000000000002dad22022121d689f57fb38ca21349", + "0x000000000000000000000000000000c9f189f2a91aeb664ce376d8b157ba98f8", + "0x00000000000000000000000000000000002531a51ad54f124d58094b219818d2", + "0x000000000000000000000000000000ef1e6db71809307f677677e62b4163f556", + "0x0000000000000000000000000000000000272da4396fb2a7ee0638b9140e523d", + "0x0000000000000000000000000000002e54c0244a7732c87bc4712a76dd8c83fb", + "0x000000000000000000000000000000000007db77b3e04b7eba9643da57cbbe4d", + "0x000000000000000000000000000000e0dfe1ddd7f74ae0d636c910c3e85830d8", + "0x00000000000000000000000000000000000466fa9b57ec4664abd1505b490862", + "0x0000000000000000000000000000009ee55ae8a32fe5384c79907067cc27192e", + "0x00000000000000000000000000000000000799d0e465cec07ecb5238c854e830", + "0x0000000000000000000000000000001d5910ad361e76e1c241247a823733c39f", + "0x00000000000000000000000000000000002b03f2ccf7507564da2e6678bef8fe", + "0x000000000000000000000000000000ee40d90bea71fba7a412dd61fcf34e8ceb", + "0x0000000000000000000000000000000000140b0936c323fd2471155617b6af56", + "0x0000000000000000000000000000002b90071823185c5ff8e440fd3d73b6fefc", + "0x00000000000000000000000000000000002b6c10790a5f6631c87d652e059df4", + "0x00000000000000000000000000000029a17181c7934fc3fdbd352eac5cb521b9", + "0x00000000000000000000000000000000001f497cbf5284ff29a2d336e5991999", + "0x000000000000000000000000000000072bd9c0c6beda1fdee6d4ff0432ba9e1b", + "0x000000000000000000000000000000000013ea38a0bd2aa751a490a724fac818", + "0x000000000000000000000000000000c599f63dcd3edd49f08ae5c3141c1e3493", + "0x00000000000000000000000000000000002bdb36be0bea09950dd32a8ccf6fbc", + "0x00000000000000000000000000000047f27f29724e7f19eba0340256a0bd4b7d", + "0x00000000000000000000000000000000001c1c5ccf87a962129ca785f8f35120", + "0x000000000000000000000000000000c5c71efdae00679bbe4a95096e012b1817", + "0x000000000000000000000000000000000017a365de041e317817d0135f2b48e0", + "0x0000000000000000000000000000008ae711ac402f7848d719c93a89ba8d39f1", + "0x00000000000000000000000000000000002b6fb40ed8a1935226f4f9786a0499", + "0x0000000000000000000000000000002f03a71501d83de1da5715a4e9462d6198", + "0x00000000000000000000000000000000001644064443b8546f48eae693af47b8", + "0x00000000000000000000000000000083763ab1b6e8fe269b2fe4c7b9c448c08d", + "0x000000000000000000000000000000000021d7cc18c59676a8eeb47c0111c251", + "0x000000000000000000000000000000b5f937153073e03ea7d51a996e0ebc2e6b", + "0x000000000000000000000000000000000011ddd0e26457373eb06e0493177672", + "0x000000000000000000000000000000c5f6eb9f6fc8fa99811a4a88c74a6d018b", + "0x000000000000000000000000000000000025bcd07a0732c123567834f5109558", + "0x000000000000000000000000000000aeb08a0b1a4442189448b4e97490568146", + "0x000000000000000000000000000000000002a1744e4771705536a88f07e0f90f", + "0x000000000000000000000000000000b938568293bd0724b0ea76c2ec34c4a829", + "0x0000000000000000000000000000000000053296e8f3b9ad3af877dfa9c7c2a7", + "0x000000000000000000000000000000f0ca1db6323996eba26bdc86dafef9d10b", + "0x00000000000000000000000000000000001441a46c58af03d5645d52721d956a", + "0x0000000000000000000000000000008bbf8f884013c66c28ba09c2fbd573b656", + "0x0000000000000000000000000000000000206c391ca06fac27d1908e94570243", + "0x0000000000000000000000000000002d4f5aaed88ba4f79612d53b804ca8f194", + "0x00000000000000000000000000000000001674011c96392df08970fa6b7b4cb8", + "0x0000000000000000000000000000009f88297c1729d76c4d9306853598c91325", + "0x0000000000000000000000000000000000256f51adfcacc3c1e340be4d32d3e9", + "0x0000000000000000000000000000000ab9955eec0d74eb799afed2a802b24d75", + "0x00000000000000000000000000000000001fcbe43ea105b30d36ed0b21b03411", + "0x000000000000000000000000000000d66b1d5433f1aa5305cd1edce7c22de466", + "0x00000000000000000000000000000000002331546a256b8a3b751956806680d4", + "0x000000000000000000000000000000e97954ad6cd6f45fb15c91434121db4304", + "0x00000000000000000000000000000000002e20a97e09d50f227ced47e7a98250", + "0x0000000000000000000000000000001ebbc27eb9ebededefba79522eb58ae89b", + "0x0000000000000000000000000000000000090efa4974e566e81d1177b85a30be", + "0x0000000000000000000000000000005eafa070b9c9632404052642e3bc14f9fd", + "0x00000000000000000000000000000000001489068864102daca6a6b8bc4d448b", + "0x0000000000000000000000000000009ebc91aaaac036a6477cadbe54e8556dfd", + "0x00000000000000000000000000000000000ef6d835e2ed3343b95c82c8c54037", + "0x00000000000000000000000000000033b28b529dff46e93af4e7422530478e4a", + "0x000000000000000000000000000000000020a86c2f8591bf190bcddcc03c42fb", + "0x000000000000000000000000000000a9679d0acc088f7dc27bf6d866bcd2dda2", + "0x00000000000000000000000000000000002fb9d0d2d4099402bed74f738f64cc", + "0x00000000000000000000000000000023b09f876a29a061582848a8b9a5870c12", + "0x00000000000000000000000000000000001d5bb906f03f0d49e9c4791bc43af9", + "0x00000000000000000000000000000017aac9854ea240d8ec97bf760c4d4ba870", + "0x00000000000000000000000000000000000b227a556c414ada0dc75bb303e30e", + "0x0000000000000000000000000000000000000000000000000000000000000001", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000000000000000000000000000000000000002", + "0x0000000000000000000000000000000000000000000000000000000000000000", + "0x0000000000000000000000000000009b624fa65d1a24b7f14a8f25f3789622af", + "0x000000000000000000000000000000000013d47bff8c630e847b70e2732fd3f0", + "0x00000000000000000000000000000061d21663e93132f32921075f4c936a84df", + "0x00000000000000000000000000000000001a74ca4e118fb480b9b999902989a3", +] diff --git a/noir/noir-repo/tooling/lsp/src/requests/completion.rs b/noir/noir-repo/tooling/lsp/src/requests/completion.rs index c59544a36ea..49608c2e06a 100644 --- a/noir/noir-repo/tooling/lsp/src/requests/completion.rs +++ b/noir/noir-repo/tooling/lsp/src/requests/completion.rs @@ -17,10 +17,11 @@ use noirc_frontend::{ ast::{ AsTraitPath, AttributeTarget, BlockExpression, CallExpression, ConstructorExpression, Expression, ExpressionKind, ForLoopStatement, GenericTypeArgs, Ident, IfExpression, - ItemVisibility, LValue, Lambda, LetStatement, MemberAccessExpression, MethodCallExpression, - NoirFunction, NoirStruct, NoirTraitImpl, Path, PathKind, Pattern, Statement, - TraitImplItemKind, TypeImpl, UnresolvedGeneric, UnresolvedGenerics, UnresolvedType, - UnresolvedTypeData, UseTree, UseTreeKind, Visitor, + IntegerBitSize, ItemVisibility, LValue, Lambda, LetStatement, MemberAccessExpression, + MethodCallExpression, NoirFunction, NoirStruct, NoirTraitImpl, Path, PathKind, Pattern, + Signedness, Statement, TraitImplItemKind, TypeImpl, TypePath, UnresolvedGeneric, + UnresolvedGenerics, UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression, UseTree, + UseTreeKind, Visitor, }, graph::{CrateId, Dependency}, hir::def_map::{CrateDefMap, LocalModuleId, ModuleId}, @@ -28,8 +29,8 @@ use noirc_frontend::{ macros_api::{ModuleDefId, NodeInterner}, node_interner::ReferenceId, parser::{Item, ItemKind, ParsedSubModule}, - token::CustomAttribute, - ParsedModule, StructType, Type, TypeBinding, + token::{CustomAttribute, Token, Tokens}, + Kind, ParsedModule, StructType, Type, TypeBinding, }; use sort_text::underscore_sort_text; @@ -362,6 +363,8 @@ impl<'a> NodeFinder<'a> { self.local_variables_completion(&prefix); self.builtin_functions_completion(&prefix, function_completion_kind); self.builtin_values_completion(&prefix); + self.builtin_types_completion(&prefix); + self.type_parameters_completion(&prefix); if let Some(self_type) = &self.self_type { let self_prefix = true; self.complete_type_fields_and_methods( @@ -627,7 +630,15 @@ impl<'a> NodeFinder<'a> { }; for (name, methods) in methods_by_name { - for func_id in methods.iter() { + for (func_id, method_type) in methods.iter() { + if function_kind == FunctionKind::Any { + if let Some(method_type) = method_type { + if method_type.unify(typ).is_err() { + continue; + } + } + } + if name_matches(name, prefix) { let completion_items = self.function_completion_items( name, @@ -1553,6 +1564,44 @@ impl<'a> Visitor for NodeFinder<'a> { false } + fn visit_type_path(&mut self, type_path: &TypePath, _: Span) -> bool { + if type_path.item.span().end() as usize != self.byte_index { + return true; + } + + let typ = match &type_path.typ.typ { + UnresolvedTypeData::FieldElement => Some(Type::FieldElement), + UnresolvedTypeData::Integer(signedness, integer_bit_size) => { + Some(Type::Integer(*signedness, *integer_bit_size)) + } + UnresolvedTypeData::Bool => Some(Type::Bool), + UnresolvedTypeData::String(UnresolvedTypeExpression::Constant(value, _)) => { + Some(Type::String(Box::new(Type::Constant( + *value, + Kind::Numeric(Box::new(Type::Integer( + Signedness::Unsigned, + IntegerBitSize::ThirtyTwo, + ))), + )))) + } + UnresolvedTypeData::Quoted(quoted_type) => Some(Type::Quoted(*quoted_type)), + _ => None, + }; + + if let Some(typ) = typ { + let prefix = &type_path.item.0.contents; + self.complete_type_methods( + &typ, + prefix, + FunctionKind::Any, + FunctionCompletionKind::NameAndParameters, + false, // self_prefix + ); + } + + false + } + fn visit_custom_attribute(&mut self, attribute: &CustomAttribute, target: AttributeTarget) { if self.byte_index != attribute.contents_span.end() as usize { return; @@ -1560,6 +1609,39 @@ impl<'a> Visitor for NodeFinder<'a> { self.suggest_attributes(&attribute.contents, target); } + + fn visit_quote(&mut self, tokens: &Tokens) { + let mut last_was_dollar = false; + + for token in &tokens.0 { + let span = token.to_span(); + if span.end() as usize > self.byte_index { + break; + } + + let token = token.token(); + + if let Token::DollarSign = token { + if span.end() as usize == self.byte_index { + self.local_variables_completion(""); + break; + } + + last_was_dollar = true; + continue; + } + + if span.end() as usize == self.byte_index { + let prefix = token.to_string(); + if last_was_dollar { + self.local_variables_completion(&prefix); + } + break; + } + + last_was_dollar = false; + } + } } fn get_field_type(typ: &Type, name: &str) -> Option { diff --git a/noir/noir-repo/tooling/lsp/src/requests/completion/tests.rs b/noir/noir-repo/tooling/lsp/src/requests/completion/tests.rs index 7c596bccd11..45eb79bd1c2 100644 --- a/noir/noir-repo/tooling/lsp/src/requests/completion/tests.rs +++ b/noir/noir-repo/tooling/lsp/src/requests/completion/tests.rs @@ -431,6 +431,27 @@ mod completion_tests { .await; } + #[test] + async fn test_complete_type_path_with_non_empty_name() { + let src = r#" + trait One { + fn one() -> Self; + } + + impl One for Field { + fn one() -> Self { + 1 + } + } + + fn main() { + Field::o>|< + } + "#; + assert_completion(src, vec![function_completion_item("one()", "one()", "fn() -> Field")]) + .await; + } + #[test] async fn test_complete_function_without_arguments() { let src = r#" @@ -756,6 +777,18 @@ mod completion_tests { ); } + #[test] + async fn test_suggest_builtin_types_in_any_position() { + let src = r#" + fn foo() { + i>|< + } + "#; + + let items = get_completions(src).await; + assert!(items.iter().any(|item| item.label == "i8")); + } + #[test] async fn test_suggest_true() { let src = r#" @@ -763,15 +796,11 @@ mod completion_tests { let x = t>|< } "#; - assert_completion_excluding_auto_import( - src, - vec![simple_completion_item( - "true", - CompletionItemKind::KEYWORD, - Some("bool".to_string()), - )], - ) - .await; + + let items = get_completions(src).await; + assert!(items + .iter() + .any(|item| item.label == "true" && item.kind == Some(CompletionItemKind::KEYWORD))); } #[test] @@ -2174,4 +2203,52 @@ mod completion_tests { assert_eq!(completions.len(), 1); assert_eq!(completions[0].label, "unquote!(…)"); } + + #[test] + async fn test_suggests_variable_in_quoted_after_dollar() { + let src = r#" + fn main() { + comptime { + let some_var = 1; + quote { + $>|< + } + } + } + "#; + + assert_completion( + src, + vec![simple_completion_item( + "some_var", + CompletionItemKind::VARIABLE, + Some("Field".to_string()), + )], + ) + .await; + } + + #[test] + async fn test_suggests_variable_in_quoted_after_dollar_and_letters() { + let src = r#" + fn main() { + comptime { + let some_var = 1; + quote { + $s>|< + } + } + } + "#; + + assert_completion( + src, + vec![simple_completion_item( + "some_var", + CompletionItemKind::VARIABLE, + Some("Field".to_string()), + )], + ) + .await; + } } diff --git a/noir/noir-repo/tooling/lsp/src/requests/mod.rs b/noir/noir-repo/tooling/lsp/src/requests/mod.rs index c8d3e2f5f0e..576d026081d 100644 --- a/noir/noir-repo/tooling/lsp/src/requests/mod.rs +++ b/noir/noir-repo/tooling/lsp/src/requests/mod.rs @@ -238,7 +238,11 @@ pub(crate) fn on_initialize( )), completion_provider: Some(lsp_types::OneOf::Right(lsp_types::CompletionOptions { resolve_provider: None, - trigger_characters: Some(vec![".".to_string(), ":".to_string()]), + trigger_characters: Some(vec![ + ".".to_string(), // For method calls + ":".to_string(), // For paths + "$".to_string(), // For $var inside `quote { ... }` + ]), all_commit_characters: None, work_done_progress_options: WorkDoneProgressOptions { work_done_progress: None, diff --git a/noir/noir-repo/tooling/lsp/src/requests/signature_help.rs b/noir/noir-repo/tooling/lsp/src/requests/signature_help.rs index 8f1bbb1570f..b075fea1d1e 100644 --- a/noir/noir-repo/tooling/lsp/src/requests/signature_help.rs +++ b/noir/noir-repo/tooling/lsp/src/requests/signature_help.rs @@ -8,8 +8,8 @@ use lsp_types::{ use noirc_errors::{Location, Span}; use noirc_frontend::{ ast::{ - CallExpression, ConstrainKind, ConstrainStatement, Expression, ExpressionKind, - FunctionReturnType, MethodCallExpression, Statement, Visitor, + CallExpression, ConstrainKind, ConstrainStatement, Expression, FunctionReturnType, + MethodCallExpression, Statement, Visitor, }, hir_def::{function::FuncMeta, stmt::HirPattern}, macros_api::NodeInterner, @@ -375,39 +375,24 @@ impl<'a> Visitor for SignatureFinder<'a> { return false; } - let arguments_span = if let Some(expr) = &constrain_statement.1 { - Span::from(constrain_statement.0.span.start()..expr.span.end()) - } else { - constrain_statement.0.span - }; + let kind_len = constrain_statement.kind.to_string().len() as u32; + let span = constrain_statement.span; + let arguments_span = Span::from(span.start() + kind_len + 1..span.end() - 1); if !self.includes_span(arguments_span) { return false; } - match constrain_statement.2 { - ConstrainKind::Assert => { - let mut arguments = vec![constrain_statement.0.clone()]; - if let Some(expr) = &constrain_statement.1 { - arguments.push(expr.clone()); - } + let active_parameter = self.compute_active_parameter(&constrain_statement.arguments); - let active_parameter = self.compute_active_parameter(&arguments); + match constrain_statement.kind { + ConstrainKind::Assert => { let signature_information = self.assert_signature_information(active_parameter); self.set_signature_help(signature_information); } ConstrainKind::AssertEq => { - if let ExpressionKind::Infix(infix) = &constrain_statement.0.kind { - let mut arguments = vec![infix.lhs.clone(), infix.rhs.clone()]; - if let Some(expr) = &constrain_statement.1 { - arguments.push(expr.clone()); - } - - let active_parameter = self.compute_active_parameter(&arguments); - let signature_information = - self.assert_eq_signature_information(active_parameter); - self.set_signature_help(signature_information); - } + let signature_information = self.assert_eq_signature_information(active_parameter); + self.set_signature_help(signature_information); } ConstrainKind::Constrain => (), } diff --git a/noir/noir-repo/tooling/nargo_fmt/src/visitor/stmt.rs b/noir/noir-repo/tooling/nargo_fmt/src/visitor/stmt.rs index b5ac14a33b3..8908aabd87c 100644 --- a/noir/noir-repo/tooling/nargo_fmt/src/visitor/stmt.rs +++ b/noir/noir-repo/tooling/nargo_fmt/src/visitor/stmt.rs @@ -2,9 +2,7 @@ use std::iter::zip; use noirc_frontend::macros_api::Span; -use noirc_frontend::ast::{ - ConstrainKind, ConstrainStatement, ExpressionKind, ForRange, Statement, StatementKind, -}; +use noirc_frontend::ast::{ConstrainKind, ConstrainStatement, ForRange, Statement, StatementKind}; use crate::{rewrite, visitor::expr::wrap_exprs}; @@ -38,37 +36,21 @@ impl super::FmtVisitor<'_> { self.push_rewrite(format!("{let_str} {expr_str};"), span); } - StatementKind::Constrain(ConstrainStatement(expr, message, kind)) => { + StatementKind::Constrain(ConstrainStatement { kind, arguments, span: _ }) => { let mut nested_shape = self.shape(); let shape = nested_shape; nested_shape.indent.block_indent(self.config); - let message = message.map_or(String::new(), |message| { - let message = rewrite::sub_expr(self, nested_shape, message); - format!(", {message}") - }); - - let (callee, args) = match kind { - ConstrainKind::Assert | ConstrainKind::Constrain => { - let assertion = rewrite::sub_expr(self, nested_shape, expr); - let args = format!("{assertion}{message}"); - - ("assert", args) - } - ConstrainKind::AssertEq => { - if let ExpressionKind::Infix(infix) = expr.kind { - let lhs = rewrite::sub_expr(self, nested_shape, infix.lhs); - let rhs = rewrite::sub_expr(self, nested_shape, infix.rhs); - - let args = format!("{lhs}, {rhs}{message}"); - - ("assert_eq", args) - } else { - unreachable!() - } - } + let callee = match kind { + ConstrainKind::Assert | ConstrainKind::Constrain => "assert", + ConstrainKind::AssertEq => "assert_eq", }; + let args = arguments + .into_iter() + .map(|arg| rewrite::sub_expr(self, nested_shape, arg)) + .collect::>() + .join(", "); let args = wrap_exprs( "(", diff --git a/noir/noir-repo/tooling/noir_js/scripts/compile_test_programs.sh b/noir/noir-repo/tooling/noir_js/scripts/compile_test_programs.sh index 0642159aa69..c65aea823a4 100755 --- a/noir/noir-repo/tooling/noir_js/scripts/compile_test_programs.sh +++ b/noir/noir-repo/tooling/noir_js/scripts/compile_test_programs.sh @@ -5,3 +5,4 @@ nargo --program-dir ./test/noir_compiled_examples/assert_lt compile --force nargo --program-dir ./test/noir_compiled_examples/assert_msg_runtime compile --force nargo --program-dir ./test/noir_compiled_examples/fold_fibonacci compile --force nargo --program-dir ./test/noir_compiled_examples/assert_raw_payload compile --force +nargo --program-dir ./test/noir_compiled_examples/databus compile --force diff --git a/noir/noir-repo/tooling/noir_js/test/node/execute.test.ts b/noir/noir-repo/tooling/noir_js/test/node/execute.test.ts index 7c93a911042..ceac21b2860 100644 --- a/noir/noir-repo/tooling/noir_js/test/node/execute.test.ts +++ b/noir/noir-repo/tooling/noir_js/test/node/execute.test.ts @@ -2,6 +2,7 @@ import assert_lt_json from '../noir_compiled_examples/assert_lt/target/assert_lt import assert_msg_json from '../noir_compiled_examples/assert_msg_runtime/target/assert_msg_runtime.json' assert { type: 'json' }; import fold_fibonacci_json from '../noir_compiled_examples/fold_fibonacci/target/fold_fibonacci.json' assert { type: 'json' }; import assert_raw_payload_json from '../noir_compiled_examples/assert_raw_payload/target/assert_raw_payload.json' assert { type: 'json' }; +import databus_json from '../noir_compiled_examples/databus/target/databus.json' assert { type: 'json' }; import { Noir, ErrorWithPayload } from '@noir-lang/noir_js'; import { CompiledCircuit } from '@noir-lang/types'; @@ -10,6 +11,7 @@ import { expect } from 'chai'; const assert_lt_program = assert_lt_json as CompiledCircuit; const assert_msg_runtime = assert_msg_json as CompiledCircuit; const fold_fibonacci_program = fold_fibonacci_json as CompiledCircuit; +const databus_program = databus_json as CompiledCircuit; it('executes a single-ACIR program correctly', async () => { const inputs = { @@ -21,43 +23,20 @@ it('executes a single-ACIR program correctly', async () => { expect(returnValue).to.be.eq('0x05'); }); -it('circuit with a fmt string assert message should fail with the resolved assertion message', async () => { +it('successfully executes a program with multiple acir circuits', async () => { const inputs = { x: '10', - y: '5', }; - try { - await new Noir(assert_msg_runtime).execute(inputs); - } catch (error) { - const knownError = error as Error; - expect(knownError.message).to.equal('Circuit execution failed: Expected x < y but got 10 < 5'); - } -}); - -it('circuit with a raw assert payload should fail with the decoded payload', async () => { - const inputs = { - x: '7', - y: '5', - }; - try { - await new Noir(assert_raw_payload_json).execute(inputs); - } catch (error) { - const knownError = error as ErrorWithPayload; - const invalidXYErrorSelector = Object.keys(assert_raw_payload_json.abi.error_types)[0]; - expect(knownError.rawAssertionPayload!.selector).to.equal(invalidXYErrorSelector); - expect(knownError.decodedAssertionPayload).to.deep.equal({ - x: '0x07', - y: '0x05', - }); - } + expect(() => new Noir(fold_fibonacci_program).execute(inputs)).to.not.throw(); }); -it('successfully executes a program with multiple acir circuits', async () => { +it('circuit with a fmt string assert message should fail with the resolved assertion message', async () => { const inputs = { x: '10', + y: '5', }; try { - await new Noir(fold_fibonacci_program).execute(inputs); + await new Noir(assert_msg_runtime).execute(inputs); } catch (error) { const knownError = error as Error; expect(knownError.message).to.equal('Circuit execution failed: Expected x < y but got 10 < 5'); @@ -82,50 +61,12 @@ it('circuit with a raw assert payload should fail with the decoded payload', asy } }); -it('successfully executes a program with multiple acir circuits', async () => { +it('successfully decodes the return values from a program using the databus', async () => { const inputs = { - x: '10', + x: '3', + y: '4', + z: [1, 2, 3, 4], }; - try { - await new Noir(fold_fibonacci_program).execute(inputs); - } catch (error) { - const knownError = error as Error; - expect(knownError.message).to.equal('Circuit execution failed: Error: Cannot satisfy constraint'); - } -}); - -it('successfully executes a program with multiple acir circuits', async () => { - const inputs = { - x: '10', - }; - try { - await new Noir(fold_fibonacci_program).execute(inputs); - } catch (error) { - const knownError = error as Error; - expect(knownError.message).to.equal('Circuit execution failed: Error: Cannot satisfy constraint'); - } -}); - -it('successfully executes a program with multiple acir circuits', async () => { - const inputs = { - x: '10', - }; - try { - await new Noir(fold_fibonacci_program).execute(inputs); - } catch (error) { - const knownError = error as Error; - expect(knownError.message).to.equal('Circuit execution failed: Error: Cannot satisfy constraint'); - } -}); - -it('successfully executes a program with multiple acir circuits', async () => { - const inputs = { - x: '10', - }; - try { - await new Noir(fold_fibonacci_program).execute(inputs); - } catch (error) { - const knownError = error as Error; - expect(knownError.message).to.equal('Circuit execution failed: Error: Cannot satisfy constraint'); - } + const { returnValue } = await new Noir(databus_program).execute(inputs); + expect(returnValue).to.be.eq('0x09'); }); diff --git a/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/Nargo.toml b/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/Nargo.toml new file mode 100644 index 00000000000..d484b80325e --- /dev/null +++ b/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/Nargo.toml @@ -0,0 +1,5 @@ +[package] +name = "databus" +type = "bin" +authors = [""] +[dependencies] diff --git a/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/src/main.nr b/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/src/main.nr new file mode 100644 index 00000000000..ecc7794cf9e --- /dev/null +++ b/noir/noir-repo/tooling/noir_js/test/noir_compiled_examples/databus/src/main.nr @@ -0,0 +1,12 @@ +fn main(mut x: u32, y: call_data(0) u32, z: call_data(0) [u32; 4]) -> return_data u32 { + let a = z[x]; + unsafe { + a + foo(y) + } +} + +// Use an unconstrained function to force the compiler to avoid inlining +unconstrained fn foo(x: u32) -> u32 { + x + 1 +} + diff --git a/noir/noir-repo/tooling/noirc_abi/src/lib.rs b/noir/noir-repo/tooling/noirc_abi/src/lib.rs index c3e1ade04fa..39f2e935618 100644 --- a/noir/noir-repo/tooling/noirc_abi/src/lib.rs +++ b/noir/noir-repo/tooling/noirc_abi/src/lib.rs @@ -197,7 +197,12 @@ impl Abi { /// Returns whether any values are needed to be made public for verification. pub fn has_public_inputs(&self) -> bool { - self.return_type.is_some() || self.parameters.iter().any(|param| param.is_public()) + let has_public_args = self.parameters.iter().any(|param| param.is_public()); + let has_public_return = self + .return_type + .as_ref() + .map_or(false, |typ| matches!(typ.visibility, AbiVisibility::Public)); + has_public_args || has_public_return } /// Returns `true` if the ABI contains no parameters or return value. @@ -346,15 +351,7 @@ impl Abi { .copied() }) { - // We do not return value for the data bus. - if return_type.visibility == AbiVisibility::DataBus { - None - } else { - Some(decode_value( - &mut return_witness_values.into_iter(), - &return_type.abi_type, - )?) - } + Some(decode_value(&mut return_witness_values.into_iter(), &return_type.abi_type)?) } else { // Unlike for the circuit inputs, we tolerate not being able to find the witness values for the return value. // This is because the user may be decoding a partial witness map for which is hasn't been calculated yet.