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

chore: remove usage of Backend trait #2514

Merged
merged 3 commits into from
Sep 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
21 changes: 10 additions & 11 deletions crates/acvm_backend_barretenberg/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,19 @@ mod proof_system;
mod smart_contract;

#[derive(Debug, Default)]
pub struct Barretenberg;
pub struct Backend {}

impl Barretenberg {
pub fn new() -> Barretenberg {
Barretenberg
impl Backend {
pub fn new() -> Backend {
Backend {}
}
}

impl acvm::Backend for Barretenberg {}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct BackendError(#[from] Error);
pub struct BackendError(String);

#[allow(clippy::upper_case_acronyms)]
#[derive(Debug, thiserror::Error)]
enum Error {}
impl std::fmt::Display for BackendError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
42 changes: 10 additions & 32 deletions crates/acvm_backend_barretenberg/src/proof_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,18 @@ use std::path::Path;
use acvm::acir::circuit::Opcode;
use acvm::acir::{circuit::Circuit, native_types::WitnessMap, BlackBoxFunc};
use acvm::FieldElement;
use acvm::{Language, ProofSystemCompiler};
use acvm::Language;
use tempfile::tempdir;

use crate::bb::{GatesCommand, ProveCommand, VerifyCommand, WriteVkCommand};
use crate::{BackendError, Barretenberg};
use crate::{Backend, BackendError};

impl ProofSystemCompiler for Barretenberg {
type Error = BackendError;

fn np_language(&self) -> Language {
impl Backend {
pub fn np_language(&self) -> Language {
Language::PLONKCSat { width: 3 }
}

fn get_exact_circuit_size(&self, circuit: &Circuit) -> Result<u32, Self::Error> {
pub fn get_exact_circuit_size(&self, circuit: &Circuit) -> Result<u32, BackendError> {
let temp_directory = tempdir().expect("could not create a temporary directory");
let temp_directory = temp_directory.path();
let temp_dir_path_str = temp_directory.to_str().unwrap();
Expand All @@ -38,7 +36,7 @@ impl ProofSystemCompiler for Barretenberg {
Ok(number_of_gates_needed)
}

fn supports_opcode(&self, opcode: &Opcode) -> bool {
pub fn supports_opcode(&self, opcode: &Opcode) -> bool {
match opcode {
Opcode::Arithmetic(_) => true,
Opcode::Directive(_) => true,
Expand All @@ -63,14 +61,12 @@ impl ProofSystemCompiler for Barretenberg {
}
}

fn prove_with_pk(
pub fn prove(
&self,
_common_reference_string: &[u8],
circuit: &Circuit,
witness_values: WitnessMap,
_proving_key: &[u8],
is_recursive: bool,
) -> Result<Vec<u8>, Self::Error> {
) -> Result<Vec<u8>, BackendError> {
let temp_directory = tempdir().expect("could not create a temporary directory");
let temp_directory = temp_directory.path();
let temp_dir_path_str = temp_directory.to_str().unwrap();
Expand Down Expand Up @@ -116,15 +112,13 @@ impl ProofSystemCompiler for Barretenberg {
Ok(proof)
}

fn verify_with_vk(
pub fn verify(
&self,
_common_reference_string: &[u8],
proof: &[u8],
public_inputs: WitnessMap,
circuit: &Circuit,
_verification_key: &[u8],
is_recursive: bool,
) -> Result<bool, Self::Error> {
) -> Result<bool, BackendError> {
let temp_directory = tempdir().expect("could not create a temporary directory");
let temp_directory = temp_directory.path();
let temp_dir_path = temp_directory.to_str().unwrap();
Expand Down Expand Up @@ -172,22 +166,6 @@ impl ProofSystemCompiler for Barretenberg {
}
.run())
}

fn proof_as_fields(
&self,
_proof: &[u8],
_public_inputs: WitnessMap,
) -> Result<Vec<FieldElement>, Self::Error> {
kevaundray marked this conversation as resolved.
Show resolved Hide resolved
panic!("vk_as_fields not supported in this backend");
}

fn vk_as_fields(
&self,
_common_reference_string: &[u8],
_verification_key: &[u8],
) -> Result<(Vec<FieldElement>, FieldElement), Self::Error> {
panic!("vk_as_fields not supported in this backend");
}
}

pub(super) fn write_to_file(bytes: &[u8], path: &Path) -> String {
Expand Down
33 changes: 10 additions & 23 deletions crates/acvm_backend_barretenberg/src/smart_contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,16 @@ use super::proof_system::{serialize_circuit, write_to_file};
use crate::{
bb::{ContractCommand, WriteVkCommand},
proof_system::read_bytes_from_file,
BackendError, Barretenberg,
Backend, BackendError,
};
use acvm::{acir::circuit::Circuit, SmartContract};
use acvm::acir::circuit::Circuit;
use tempfile::tempdir;

/// Embed the Solidity verifier file
const ULTRA_VERIFIER_CONTRACT: &str = include_str!("contract.sol");

impl SmartContract for Barretenberg {
type Error = BackendError;

fn eth_contract_from_vk(
&self,
_common_reference_string: &[u8],
circuit: &Circuit,
_verification_key: &[u8],
) -> Result<String, Self::Error> {
impl Backend {
pub fn eth_contract(&self, circuit: &Circuit) -> Result<String, BackendError> {
let temp_directory = tempdir().expect("could not create a temporary directory");
let temp_directory_path = temp_directory.path();
let temp_dir_path = temp_directory_path.to_str().unwrap();
Expand Down Expand Up @@ -62,18 +55,15 @@ impl SmartContract for Barretenberg {
mod tests {
use std::collections::BTreeSet;

use acvm::{
acir::{
circuit::{Circuit, Opcode, PublicInputs},
native_types::{Expression, Witness},
},
SmartContract,
use acvm::acir::{
circuit::{Circuit, Opcode, PublicInputs},
native_types::{Expression, Witness},
};

#[test]
#[serial_test::serial]
fn test_smart_contract() {
use crate::Barretenberg;
use crate::Backend;

let expression = &(Witness(1) + Witness(2)) - &Expression::from(Witness(3));
let constraint = Opcode::Arithmetic(expression);
Expand All @@ -86,12 +76,9 @@ mod tests {
return_values: PublicInputs::default(),
};

let bb = Barretenberg;
let bb = Backend::default();

let common_reference_string = Vec::new();
let verification_key = Vec::new();
let contract =
bb.eth_contract_from_vk(&common_reference_string, &circuit, &verification_key).unwrap();
let contract = bb.eth_contract(&circuit).unwrap();

assert!(contract.contains("contract BaseUltraVerifier"));
assert!(contract.contains("contract UltraVerifier"));
Expand Down
2 changes: 1 addition & 1 deletion crates/nargo_cli/src/backends.rs
Original file line number Diff line number Diff line change
@@ -1 +1 @@
pub(crate) use acvm_backend_barretenberg::Barretenberg as ConcreteBackend;
pub(crate) use acvm_backend_barretenberg::Backend;
9 changes: 5 additions & 4 deletions crates/nargo_cli/src/cli/check_cmd.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::backends::Backend;
use crate::errors::{CliError, CompileError};
use acvm::Backend;

use clap::Args;
use iter_extended::btree_map;
use nargo::{package::Package, prepare_package};
Expand Down Expand Up @@ -29,11 +30,11 @@ pub(crate) struct CheckCommand {
compile_options: CompileOptions,
}

pub(crate) fn run<B: Backend>(
_backend: &B,
pub(crate) fn run(
_backend: &Backend,
args: CheckCommand,
config: NargoConfig,
) -> Result<(), CliError<B>> {
) -> Result<(), CliError> {
let toml_path = get_package_manifest(&config.program_dir)?;
let default_selection =
if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll };
Expand Down
20 changes: 10 additions & 10 deletions crates/nargo_cli/src/cli/codegen_verifier_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,12 @@ use super::{
compile_cmd::compile_package,
fs::{create_named_dir, program::read_program_from_file, write_to_file},
};
use crate::backends::Backend;
use crate::errors::CliError;
use acvm::Backend;

use clap::Args;
use nargo::artifacts::program::PreprocessedProgram;
use nargo::{ops::codegen_verifier, package::Package};
use nargo::package::Package;
use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection};
use noirc_driver::CompileOptions;
use noirc_frontend::graph::CrateName;
Expand All @@ -32,11 +33,11 @@ pub(crate) struct CodegenVerifierCommand {
compile_options: CompileOptions,
}

pub(crate) fn run<B: Backend>(
backend: &B,
pub(crate) fn run(
backend: &Backend,
args: CodegenVerifierCommand,
config: NargoConfig,
) -> Result<(), CliError<B>> {
) -> Result<(), CliError> {
let toml_path = get_package_manifest(&config.program_dir)?;
let default_selection =
if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll };
Expand Down Expand Up @@ -64,12 +65,12 @@ pub(crate) fn run<B: Backend>(
Ok(())
}

fn smart_contract_for_package<B: Backend>(
backend: &B,
fn smart_contract_for_package(
backend: &Backend,
package: &Package,
circuit_build_path: PathBuf,
compile_options: &CompileOptions,
) -> Result<String, CliError<B>> {
) -> Result<String, CliError> {
let preprocessed_program = if circuit_build_path.exists() {
read_program_from_file(circuit_build_path)?
} else {
Expand All @@ -82,8 +83,7 @@ fn smart_contract_for_package<B: Backend>(
}
};

let smart_contract_string = codegen_verifier(backend, &preprocessed_program.bytecode)
.map_err(CliError::SmartContractError)?;
let smart_contract_string = backend.eth_contract(&preprocessed_program.bytecode)?;

Ok(smart_contract_string)
}
27 changes: 14 additions & 13 deletions crates/nargo_cli/src/cli/compile_cmd.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use acvm::{acir::circuit::Circuit, compiler::AcirTransformationMap, Backend};
use acvm::{acir::circuit::Circuit, compiler::AcirTransformationMap};
use iter_extended::{try_vecmap, vecmap};
use nargo::artifacts::contract::PreprocessedContractFunction;
use nargo::artifacts::debug::DebugArtifact;
Expand All @@ -17,6 +17,7 @@ use noirc_frontend::hir::Context;

use clap::Args;

use crate::backends::Backend;
use crate::errors::{CliError, CompileError};

use super::fs::program::{
Expand Down Expand Up @@ -50,11 +51,11 @@ pub(crate) struct CompileCommand {
compile_options: CompileOptions,
}

pub(crate) fn run<B: Backend>(
backend: &B,
pub(crate) fn run(
backend: &Backend,
args: CompileCommand,
config: NargoConfig,
) -> Result<(), CliError<B>> {
) -> Result<(), CliError> {
let toml_path = get_package_manifest(&config.program_dir)?;
let default_selection =
if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll };
Expand Down Expand Up @@ -141,8 +142,8 @@ pub(crate) fn run<B: Backend>(
Ok(())
}

pub(crate) fn compile_package<B: Backend>(
backend: &B,
pub(crate) fn compile_package(
backend: &Backend,
package: &Package,
compile_options: &CompileOptions,
) -> Result<(Context, CompiledProgram), CompileError> {
Expand All @@ -164,10 +165,10 @@ pub(crate) fn compile_package<B: Backend>(
Ok((context, program))
}

pub(super) fn optimize_circuit<B: Backend>(
backend: &B,
pub(super) fn optimize_circuit(
backend: &Backend,
circuit: Circuit,
) -> Result<(Circuit, AcirTransformationMap), CliError<B>> {
) -> Result<(Circuit, AcirTransformationMap), CliError> {
let result = acvm::compiler::compile(circuit, backend.np_language(), |opcode| {
backend.supports_opcode(opcode)
})
Expand All @@ -176,15 +177,15 @@ pub(super) fn optimize_circuit<B: Backend>(
Ok(result)
}

pub(super) fn optimize_contract<B: Backend>(
backend: &B,
pub(super) fn optimize_contract(
backend: &Backend,
contract: CompiledContract,
) -> Result<CompiledContract, CliError<B>> {
) -> Result<CompiledContract, CliError> {
let functions = try_vecmap(contract.functions, |mut func| {
let (optimized_bytecode, location_map) = optimize_circuit(backend, func.bytecode)?;
func.bytecode = optimized_bytecode;
func.debug.update_acir(location_map);
Ok::<_, CliError<B>>(func)
Ok::<_, CliError>(func)
})?;

Ok(CompiledContract { functions, ..contract })
Expand Down
Loading