Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: simplify constant calls to poseidon2_permutation, schnorr_verify and embedded_curve_add #5140

Merged
merged 25 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
d6fae8a
feat: perform any constant pedersen blackbox functions at compile-time
TomAFrench May 29, 2024
243d158
chore: fix test relying on pedersen commitments not being calculated …
TomAFrench May 29, 2024
9b7c4bc
chore: gracefully fail when unable to simplify pedersen functions
TomAFrench Jun 10, 2024
726b2ac
chore: add simplification for more blackbox functions
TomAFrench Jun 10, 2024
0ba04e5
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jun 12, 2024
65d57d5
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jun 19, 2024
cb155e5
chore: fix build
TomAFrench Jun 19, 2024
4aa0cef
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jul 10, 2024
8c7aa7b
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jul 11, 2024
1ff2194
.
TomAFrench Jul 11, 2024
cd7fb0d
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jul 15, 2024
21a756d
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Jul 19, 2024
7425c1b
.
TomAFrench Jul 19, 2024
dda132c
.
TomAFrench Jul 19, 2024
dcc5982
.
TomAFrench Jul 19, 2024
7d3e2e8
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Aug 10, 2024
603088a
.
TomAFrench Aug 21, 2024
25deec0
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Aug 21, 2024
386a785
Merge branch 'master' into tf/more-comptime-optimization
TomAFrench Aug 28, 2024
7ea10b9
.
TomAFrench Aug 28, 2024
4505a9c
.
TomAFrench Aug 28, 2024
d97effe
.
TomAFrench Aug 28, 2024
9ed1919
.
TomAFrench Aug 28, 2024
de51683
.
TomAFrench Aug 28, 2024
40871e1
Update compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variabl…
TomAFrench Aug 28, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ criterion = "0.5.0"
# https://github.com/tikv/pprof-rs/pull/172
pprof = { version = "0.13", features = ["flamegraph", "criterion"] }


cfg-if = "1.0.0"
dirs = "4"
serde = { version = "1.0.136", features = ["derive"] }
serde_json = "1.0"
Expand Down
4 changes: 4 additions & 0 deletions compiler/noirc_driver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ tracing.workspace = true
thiserror.workspace = true

aztec_macros = { path = "../../aztec_macros" }

[features]
bn254 = ["noirc_frontend/bn254", "noirc_evaluator/bn254"]
bls12_381 = ["noirc_frontend/bls12_381", "noirc_evaluator/bls12_381"]
6 changes: 6 additions & 0 deletions compiler/noirc_evaluator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ license.workspace = true
noirc_frontend.workspace = true
noirc_errors.workspace = true
acvm.workspace = true
bn254_blackbox_solver = { workspace = true, optional = true }
fxhash.workspace = true
iter-extended.workspace = true
thiserror.workspace = true
Expand All @@ -20,3 +21,8 @@ im.workspace = true
serde.workspace = true
tracing.workspace = true
chrono = "0.4.37"
cfg-if.workspace = true

[features]
bn254 = ["dep:bn254_blackbox_solver", "noirc_frontend/bn254"]
bls12_381= []
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ use crate::ssa::ir::{instruction::Endian, types::NumericType};
use acvm::acir::circuit::brillig::{BrilligInputs, BrilligOutputs};
use acvm::acir::circuit::opcodes::{BlockId, BlockType, MemOp};
use acvm::acir::circuit::{AssertionPayload, ExpressionOrMemory, Opcode};
use acvm::blackbox_solver;
use acvm::brillig_vm::{MemoryValue, VMStatus, VM};
use acvm::{
acir::AcirField,
Expand Down Expand Up @@ -1994,7 +1993,14 @@ fn execute_brillig(
}

// Instantiate a Brillig VM given the solved input registers and memory, along with the Brillig bytecode.
let mut vm = VM::new(calldata, code, Vec::new(), &blackbox_solver::StubbedBlackBoxSolver);
cfg_if::cfg_if! {
if #[cfg(feature = "bn254")] {
let solver = bn254_blackbox_solver::Bn254BlackBoxSolver;
} else {
let solver = acvm::blackbox_solver::StubbedBlackBoxSolver;
}
};
let mut vm = VM::new(calldata, code, Vec::new(), &solver);

// Run the Brillig VM on these inputs, bytecode, etc!
let vm_status = vm.process_opcodes();
Expand Down
74 changes: 71 additions & 3 deletions compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
use fxhash::FxHashMap as HashMap;
use std::{collections::VecDeque, rc::Rc};

use acvm::{acir::AcirField, acir::BlackBoxFunc, BlackBoxResolutionError, FieldElement};
use acvm::{
acir::{AcirField, BlackBoxFunc},
BlackBoxFunctionSolver, BlackBoxResolutionError, FieldElement,
};
use iter_extended::vecmap;
use num_bigint::BigUint;

Expand Down Expand Up @@ -434,6 +437,13 @@ fn simplify_black_box_func(
arguments: &[ValueId],
dfg: &mut DataFlowGraph,
) -> SimplifyResult {
cfg_if::cfg_if! {
if #[cfg(feature = "bn254")] {
let solver = bn254_blackbox_solver::Bn254BlackBoxSolver;
} else {
let solver = acvm::blackbox_solver::StubbedBlackBoxSolver;
}
};
match bb_func {
BlackBoxFunc::SHA256 => simplify_hash(dfg, arguments, acvm::blackbox_solver::sha256),
BlackBoxFunc::Blake2s => simplify_hash(dfg, arguments, acvm::blackbox_solver::blake2s),
Expand Down Expand Up @@ -466,10 +476,11 @@ fn simplify_black_box_func(
simplify_signature(dfg, arguments, acvm::blackbox_solver::ecdsa_secp256r1_verify)
}

BlackBoxFunc::PedersenCommitment => simplify_pedersen_commitment(dfg, solver, arguments),
BlackBoxFunc::PedersenHash => simplify_pedersen_hash(dfg, solver, arguments),

BlackBoxFunc::MultiScalarMul
| BlackBoxFunc::SchnorrVerify
| BlackBoxFunc::PedersenCommitment
| BlackBoxFunc::PedersenHash
| BlackBoxFunc::EmbeddedCurveAdd => {
// Currently unsolvable here as we rely on an implementation in the backend.
SimplifyResult::None
Expand Down Expand Up @@ -558,6 +569,63 @@ fn array_is_constant(dfg: &DataFlowGraph, values: &im::Vector<Id<Value>>) -> boo
values.iter().all(|value| dfg.get_numeric_constant(*value).is_some())
}

fn simplify_pedersen_commitment(
dfg: &mut DataFlowGraph,
solver: impl BlackBoxFunctionSolver<FieldElement>,
arguments: &[ValueId],
) -> SimplifyResult {
match (dfg.get_array_constant(arguments[0]), dfg.get_numeric_constant(arguments[1])) {
(Some((inputs, _)), Some(domain_separator)) if array_is_constant(dfg, &inputs) => {
let input_fields: Vec<_> = inputs
.iter()
.map(|id| {
dfg.get_numeric_constant(*id)
.expect("value id from array should point at constant")
})
.collect();

let (result_x, result_y) = solver
.pedersen_commitment(&input_fields, domain_separator.to_u128() as u32)
.expect("Rust solvable black box function should not fail");

let result_x = dfg.make_constant(result_x, Type::field());
let result_y = dfg.make_constant(result_y, Type::field());

let typ = Type::Array(Rc::new(vec![Type::field()]), 2);
let result_array = dfg.make_array(im::vector![result_x, result_y], typ);

SimplifyResult::SimplifiedTo(result_array)
}
_ => SimplifyResult::None,
}
}

fn simplify_pedersen_hash(
dfg: &mut DataFlowGraph,
solver: impl BlackBoxFunctionSolver<FieldElement>,
arguments: &[ValueId],
) -> SimplifyResult {
match (dfg.get_array_constant(arguments[0]), dfg.get_numeric_constant(arguments[1])) {
(Some((inputs, _)), Some(domain_separator)) if array_is_constant(dfg, &inputs) => {
let input_fields: Vec<_> = inputs
.iter()
.map(|id| {
dfg.get_numeric_constant(*id)
.expect("value id from array should point at constant")
})
.collect();

let hash = solver
.pedersen_hash(&input_fields, domain_separator.to_u128() as u32)
.expect("Rust solvable black box function should not fail");

let hash_value = dfg.make_constant(hash, Type::field());
SimplifyResult::SimplifiedTo(hash_value)
}
_ => SimplifyResult::None,
}
}

fn simplify_hash(
dfg: &mut DataFlowGraph,
arguments: &[ValueId],
Expand Down
15 changes: 3 additions & 12 deletions compiler/noirc_evaluator/src/ssa/opt/flatten_cfg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,7 @@ mod test {
ir::{
dfg::DataFlowGraph,
function::Function,
instruction::{BinaryOp, Instruction, Intrinsic, TerminatorInstruction},
instruction::{BinaryOp, Instruction, TerminatorInstruction},
map::Id,
types::Type,
value::{Value, ValueId},
Expand Down Expand Up @@ -1360,8 +1360,7 @@ mod test {
// Regression test for #1792
// Tests that it does not simplify a true constraint an always-false constraint
// fn main f1 {
// b0():
// v4 = call pedersen([Field 0], u32 0)
// b0(v4: [Field; 2]):
// v5 = array_get v4, index Field 0
// v6 = cast v5 as u32
// v8 = mod v6, u32 2
Expand Down Expand Up @@ -1393,15 +1392,7 @@ mod test {
let array_type = Type::Array(element_type.clone(), 1);

let zero = builder.field_constant(0_u128);
let zero_array = builder.array_constant(im::Vector::unit(zero), array_type);
let i_zero = builder.numeric_constant(0_u128, Type::unsigned(32));
let pedersen = builder
.import_intrinsic_id(Intrinsic::BlackBox(acvm::acir::BlackBoxFunc::PedersenCommitment));
let v4 = builder.insert_call(
pedersen,
vec![zero_array, i_zero],
vec![Type::Array(element_type, 2)],
)[0];
let v4 = builder.add_parameter(array_type);
let v5 = builder.insert_array_get(v4, zero, Type::field());
let v6 = builder.insert_cast(v5, Type::unsigned(32));
let i_two = builder.numeric_constant(2_u128, Type::unsigned(32));
Expand Down
2 changes: 1 addition & 1 deletion compiler/noirc_frontend/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ num-traits.workspace = true
rustc-hash = "1.1.0"
small-ord-set = "0.1.3"
regex = "1.9.1"
cfg-if = "1.0.0"
cfg-if.workspace = true
tracing.workspace = true
petgraph = "0.6"
lalrpop-util = { version = "0.20.2", features = ["lexer"] }
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "pedersen_commitment"
type = "bin"
authors = [""]

[dependencies]
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
use dep::std;

fn main() {
let commitment = std::hash::pedersen_commitment([0, 1]);
assert_eq(commitment.x, 0x054aa86a73cb8a34525e5bbed6e43ba1198e860f5f3950268f71df4591bde402);
assert_eq(commitment.y, 0x209dcfbf2cfb57f9f6046f44d71ac6faf87254afc7407c04eb621a6287cac126);
}

6 changes: 6 additions & 0 deletions test_programs/compile_success_empty/pedersen_hash/Nargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[package]
name = "pedersen_hash"
type = "bin"
authors = [""]

[dependencies]
7 changes: 7 additions & 0 deletions test_programs/compile_success_empty/pedersen_hash/src/main.nr
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use dep::std;

fn main() {
let hash = std::hash::pedersen_hash([0, 1]);
assert_eq(hash, 0x0d98561fb02ca04d00801dfdc118b2a24cea0351963587712a28d368041370e1);
}

2 changes: 1 addition & 1 deletion tooling/nargo_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ nargo_fmt.workspace = true
nargo_toml.workspace = true
noir_lsp.workspace = true
noir_debugger.workspace = true
noirc_driver.workspace = true
noirc_driver = { workspace = true, features = ["bn254"] }
noirc_frontend = { workspace = true, features = ["bn254"] }
noirc_abi.workspace = true
noirc_errors.workspace = true
Expand Down
Loading