From 98958170c9fa9b4731e33b31cb494a72bb90549e Mon Sep 17 00:00:00 2001 From: Maddiaa <47148561+Maddiaa0@users.noreply.github.com> Date: Fri, 7 Jul 2023 11:10:12 -0600 Subject: [PATCH] feat(acir)!: add `EcdsaSecp256r1` blackbox function (#408) Co-authored-by: Kevaundray Wedderburn --- Cargo.toml | 7 + acir/src/circuit/black_box_functions.rs | 4 + .../opcodes/black_box_function_call.rs | 37 ++++- acvm/Cargo.toml | 2 + acvm/src/pwg/blackbox/mod.rs | 19 ++- acvm/src/pwg/blackbox/signature/ecdsa.rs | 155 ++++++++++++++++-- brillig_vm/Cargo.toml | 1 + brillig_vm/src/black_box.rs | 115 +++++++++++-- 8 files changed, 308 insertions(+), 32 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 69552d6b4..9e52ded55 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,4 +29,11 @@ k256 = { version = "0.11.0", features = [ "sha256", "digest", "arithmetic", +] } +p256 = { version = "0.11.0", features = [ + "ecdsa", + "ecdsa-core", + "sha256", + "digest", + "arithmetic", ] } \ No newline at end of file diff --git a/acir/src/circuit/black_box_functions.rs b/acir/src/circuit/black_box_functions.rs index 27f85756a..17c990c76 100644 --- a/acir/src/circuit/black_box_functions.rs +++ b/acir/src/circuit/black_box_functions.rs @@ -39,6 +39,8 @@ pub enum BlackBoxFunc { HashToField128Security, /// Verifies a ECDSA signature over the secp256k1 curve. EcdsaSecp256k1, + /// Verifies a ECDSA signature over the secp256r1 curve. + EcdsaSecp256r1, /// Performs scalar multiplication over the embedded curve on which [`FieldElement`][acir_field::FieldElement] is defined. FixedBaseScalarMul, /// Calculates the Keccak256 hash of the inputs. @@ -69,6 +71,7 @@ impl BlackBoxFunc { BlackBoxFunc::RANGE => "range", BlackBoxFunc::Keccak256 => "keccak256", BlackBoxFunc::RecursiveAggregation => "recursive_aggregation", + BlackBoxFunc::EcdsaSecp256r1 => "ecdsa_secp256r1", } } pub fn lookup(op_name: &str) -> Option { @@ -79,6 +82,7 @@ impl BlackBoxFunc { "pedersen" => Some(BlackBoxFunc::Pedersen), "hash_to_field_128_security" => Some(BlackBoxFunc::HashToField128Security), "ecdsa_secp256k1" => Some(BlackBoxFunc::EcdsaSecp256k1), + "ecdsa_secp256r1" => Some(BlackBoxFunc::EcdsaSecp256r1), "fixed_base_scalar_mul" => Some(BlackBoxFunc::FixedBaseScalarMul), "and" => Some(BlackBoxFunc::AND), "xor" => Some(BlackBoxFunc::XOR), diff --git a/acir/src/circuit/opcodes/black_box_function_call.rs b/acir/src/circuit/opcodes/black_box_function_call.rs index 6db57dad9..c491fc888 100644 --- a/acir/src/circuit/opcodes/black_box_function_call.rs +++ b/acir/src/circuit/opcodes/black_box_function_call.rs @@ -64,6 +64,13 @@ pub enum BlackBoxFuncCall { hashed_message: Vec, output: Witness, }, + EcdsaSecp256r1 { + public_key_x: Vec, + public_key_y: Vec, + signature: Vec, + hashed_message: Vec, + output: Witness, + }, FixedBaseScalarMul { input: FunctionInput, outputs: (Witness, Witness), @@ -144,6 +151,13 @@ impl BlackBoxFuncCall { hashed_message: vec![], output: Witness(0), }, + BlackBoxFunc::EcdsaSecp256r1 => BlackBoxFuncCall::EcdsaSecp256r1 { + public_key_x: vec![], + public_key_y: vec![], + signature: vec![], + hashed_message: vec![], + output: Witness(0), + }, BlackBoxFunc::FixedBaseScalarMul => BlackBoxFuncCall::FixedBaseScalarMul { input: FunctionInput::dummy(), outputs: (Witness(0), Witness(0)), @@ -173,6 +187,7 @@ impl BlackBoxFuncCall { BlackBoxFuncCall::Pedersen { .. } => BlackBoxFunc::Pedersen, BlackBoxFuncCall::HashToField128Security { .. } => BlackBoxFunc::HashToField128Security, BlackBoxFuncCall::EcdsaSecp256k1 { .. } => BlackBoxFunc::EcdsaSecp256k1, + BlackBoxFuncCall::EcdsaSecp256r1 { .. } => BlackBoxFunc::EcdsaSecp256r1, BlackBoxFuncCall::FixedBaseScalarMul { .. } => BlackBoxFunc::FixedBaseScalarMul, BlackBoxFuncCall::Keccak256 { .. } => BlackBoxFunc::Keccak256, BlackBoxFuncCall::Keccak256VariableLength { .. } => BlackBoxFunc::Keccak256, @@ -229,6 +244,25 @@ impl BlackBoxFuncCall { inputs.extend(hashed_message.iter().copied()); inputs } + BlackBoxFuncCall::EcdsaSecp256r1 { + public_key_x, + public_key_y, + signature, + hashed_message, + .. + } => { + let mut inputs = Vec::with_capacity( + public_key_x.len() + + public_key_y.len() + + signature.len() + + hashed_message.len(), + ); + inputs.extend(public_key_x.iter().copied()); + inputs.extend(public_key_y.iter().copied()); + inputs.extend(signature.iter().copied()); + inputs.extend(hashed_message.iter().copied()); + inputs + } BlackBoxFuncCall::Keccak256VariableLength { inputs, var_message_size, .. } => { let mut inputs = inputs.clone(); inputs.push(*var_message_size); @@ -266,7 +300,8 @@ impl BlackBoxFuncCall { | BlackBoxFuncCall::XOR { output, .. } | BlackBoxFuncCall::HashToField128Security { output, .. } | BlackBoxFuncCall::SchnorrVerify { output, .. } - | BlackBoxFuncCall::EcdsaSecp256k1 { output, .. } => vec![*output], + | BlackBoxFuncCall::EcdsaSecp256k1 { output, .. } + | BlackBoxFuncCall::EcdsaSecp256r1 { output, .. } => vec![*output], BlackBoxFuncCall::FixedBaseScalarMul { outputs, .. } | BlackBoxFuncCall::Pedersen { outputs, .. } => vec![outputs.0, outputs.1], BlackBoxFuncCall::RANGE { .. } => vec![], diff --git a/acvm/Cargo.toml b/acvm/Cargo.toml index 27c9a1795..c5ea7ca66 100644 --- a/acvm/Cargo.toml +++ b/acvm/Cargo.toml @@ -22,6 +22,8 @@ blake2.workspace = true sha2.workspace = true sha3.workspace = true k256.workspace = true +p256.workspace = true + indexmap = "1.7.0" async-trait = "0.1" diff --git a/acvm/src/pwg/blackbox/mod.rs b/acvm/src/pwg/blackbox/mod.rs index 95a6e60e2..b18eb5b4d 100644 --- a/acvm/src/pwg/blackbox/mod.rs +++ b/acvm/src/pwg/blackbox/mod.rs @@ -20,7 +20,10 @@ use hash::{hash_to_field_128_security, solve_generic_256_hash_opcode}; use logic::{and, xor}; use pedersen::pedersen; use range::solve_range_opcode; -use signature::{ecdsa::secp256k1_prehashed, schnorr::schnorr_verify}; +use signature::{ + ecdsa::{secp256k1_prehashed, secp256r1_prehashed}, + schnorr::schnorr_verify, +}; /// Check if all of the inputs to the function have assignments /// @@ -130,6 +133,20 @@ pub(crate) fn solve( message, *output, ), + BlackBoxFuncCall::EcdsaSecp256r1 { + public_key_x, + public_key_y, + signature, + hashed_message: message, + output, + } => secp256r1_prehashed( + initial_witness, + public_key_x, + public_key_y, + signature, + message, + *output, + ), BlackBoxFuncCall::FixedBaseScalarMul { input, outputs } => { fixed_base_scalar_mul(backend, initial_witness, *input, *outputs) } diff --git a/acvm/src/pwg/blackbox/signature/ecdsa.rs b/acvm/src/pwg/blackbox/signature/ecdsa.rs index b53927ec7..3adff22cd 100644 --- a/acvm/src/pwg/blackbox/signature/ecdsa.rs +++ b/acvm/src/pwg/blackbox/signature/ecdsa.rs @@ -4,17 +4,6 @@ use acir::{ FieldElement, }; use blake2::digest::generic_array::GenericArray; -use k256::elliptic_curve::sec1::FromEncodedPoint; -use k256::elliptic_curve::PrimeField; - -use k256::{ecdsa::Signature, Scalar}; -use k256::{ - elliptic_curve::{ - sec1::{Coordinates, ToEncodedPoint}, - IsHigh, - }, - AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, -}; use crate::{ pwg::{insert_value, OpcodeResolution}, @@ -65,6 +54,47 @@ pub(crate) fn secp256k1_prehashed( Ok(OpcodeResolution::Solved) } +pub(crate) fn secp256r1_prehashed( + initial_witness: &mut WitnessMap, + public_key_x_inputs: &[FunctionInput], + public_key_y_inputs: &[FunctionInput], + signature_inputs: &[FunctionInput], + hashed_message_inputs: &[FunctionInput], + output: Witness, +) -> Result { + let hashed_message = to_u8_vec(initial_witness, hashed_message_inputs)?; + + let pub_key_x: [u8; 32] = + to_u8_vec(initial_witness, public_key_x_inputs)?.try_into().map_err(|_| { + OpcodeResolutionError::BlackBoxFunctionFailed( + acir::BlackBoxFunc::EcdsaSecp256r1, + format!("expected pubkey_x size 32 but received {}", public_key_x_inputs.len()), + ) + })?; + + let pub_key_y: [u8; 32] = + to_u8_vec(initial_witness, public_key_y_inputs)?.try_into().map_err(|_| { + OpcodeResolutionError::BlackBoxFunctionFailed( + acir::BlackBoxFunc::EcdsaSecp256r1, + format!("expected pubkey_y size 32 but received {}", public_key_y_inputs.len()), + ) + })?; + + let signature: [u8; 64] = + to_u8_vec(initial_witness, signature_inputs)?.try_into().map_err(|_| { + OpcodeResolutionError::BlackBoxFunctionFailed( + acir::BlackBoxFunc::EcdsaSecp256r1, + format!("expected signature size 64 but received {}", signature_inputs.len()), + ) + })?; + + let is_valid = + verify_secp256r1_ecdsa_signature(&hashed_message, &pub_key_x, &pub_key_y, &signature); + + insert_value(&output, FieldElement::from(is_valid), initial_witness)?; + Ok(OpcodeResolution::Solved) +} + /// Verify an ECDSA signature over the secp256k1 elliptic curve, given the hashed message fn verify_secp256k1_ecdsa_signature( hashed_msg: &[u8], @@ -72,6 +102,73 @@ fn verify_secp256k1_ecdsa_signature( public_key_y_bytes: &[u8; 32], signature: &[u8; 64], ) -> bool { + use k256::elliptic_curve::sec1::FromEncodedPoint; + use k256::elliptic_curve::PrimeField; + + use k256::{ecdsa::Signature, Scalar}; + use k256::{ + elliptic_curve::{ + sec1::{Coordinates, ToEncodedPoint}, + IsHigh, + }, + AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, + }; + // Convert the inputs into k256 data structures + + let signature = Signature::try_from(signature.as_slice()).unwrap(); + + let point = EncodedPoint::from_affine_coordinates( + public_key_x_bytes.into(), + public_key_y_bytes.into(), + true, + ); + let pubkey = PublicKey::from_encoded_point(&point).unwrap(); + + let z = Scalar::from_repr(*GenericArray::from_slice(hashed_msg)).unwrap(); + + // Finished converting bytes into data structures + + let r = signature.r(); + let s = signature.s(); + + // Ensure signature is "low S" normalized ala BIP 0062 + if s.is_high().into() { + return false; + } + + let s_inv = s.invert().unwrap(); + let u1 = z * s_inv; + let u2 = *r * s_inv; + + #[allow(non_snake_case)] + let R: AffinePoint = ((ProjectivePoint::GENERATOR * u1) + + (ProjectivePoint::from(*pubkey.as_affine()) * u2)) + .to_affine(); + + match R.to_encoded_point(false).coordinates() { + Coordinates::Uncompressed { x, y: _ } => Scalar::from_repr(*x).unwrap().eq(&r), + _ => unreachable!("Point is uncompressed"), + } +} +/// Verify an ECDSA signature over the secp256r1 elliptic curve, given the hashed message +fn verify_secp256r1_ecdsa_signature( + hashed_msg: &[u8], + public_key_x_bytes: &[u8; 32], + public_key_y_bytes: &[u8; 32], + signature: &[u8; 64], +) -> bool { + use p256::elliptic_curve::sec1::FromEncodedPoint; + use p256::elliptic_curve::PrimeField; + + use p256::{ecdsa::Signature, Scalar}; + use p256::{ + elliptic_curve::{ + sec1::{Coordinates, ToEncodedPoint}, + IsHigh, + }, + AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, + }; + // Convert the inputs into k256 data structures let signature = Signature::try_from(signature.as_slice()).unwrap(); @@ -112,10 +209,10 @@ fn verify_secp256k1_ecdsa_signature( #[cfg(test)] mod test { - use super::verify_secp256k1_ecdsa_signature; + use super::{verify_secp256k1_ecdsa_signature, verify_secp256r1_ecdsa_signature}; #[test] - fn verifies_valid_signature_with_low_s_value() { + fn verifies_valid_k1_signature_with_low_s_value() { // 0x3a73f4123a5cd2121f21cd7e8d358835476949d035d9c2da6806b4633ac8c1e2, let hashed_message: [u8; 32] = [ 0x3a, 0x73, 0xf4, 0x12, 0x3a, 0x5c, 0xd2, 0x12, 0x1f, 0x21, 0xcd, 0x7e, 0x8d, 0x35, @@ -151,4 +248,36 @@ mod test { assert!(valid) } + + #[test] + fn verifies_valid_r1_signature_with_low_s_value() { + // 0x54705ba3baafdbdfba8c5f9a70f7a89bee98d906b53e31074da7baecdc0da9ad + let hashed_message = [ + 84, 112, 91, 163, 186, 175, 219, 223, 186, 140, 95, 154, 112, 247, 168, 155, 238, 152, + 217, 6, 181, 62, 49, 7, 77, 167, 186, 236, 220, 13, 169, 173, + ]; + // 0x550f471003f3df97c3df506ac797f6721fb1a1fb7b8f6f83d224498a65c88e24 + let pub_key_x = [ + 85, 15, 71, 16, 3, 243, 223, 151, 195, 223, 80, 106, 199, 151, 246, 114, 31, 177, 161, + 251, 123, 143, 111, 131, 210, 36, 73, 138, 101, 200, 142, 36, + ]; + // 0x136093d7012e509a73715cbd0b00a3cc0ff4b5c01b3ffa196ab1fb327036b8e6 + let pub_key_y = [ + 19, 96, 147, 215, 1, 46, 80, 154, 115, 113, 92, 189, 11, 0, 163, 204, 15, 244, 181, + 192, 27, 63, 250, 25, 106, 177, 251, 50, 112, 54, 184, 230, + ]; + + // 0x2c70a8d084b62bfc5ce03641caf9f72ad4da8c81bfe6ec9487bb5e1bef62a13218ad9ee29eaf351fdc50f1520c425e9b908a07278b43b0ec7b872778c14e0784 + let signature: [u8; 64] = [ + 44, 112, 168, 208, 132, 182, 43, 252, 92, 224, 54, 65, 202, 249, 247, 42, 212, 218, + 140, 129, 191, 230, 236, 148, 135, 187, 94, 27, 239, 98, 161, 50, 24, 173, 158, 226, + 158, 175, 53, 31, 220, 80, 241, 82, 12, 66, 94, 155, 144, 138, 7, 39, 139, 67, 176, + 236, 123, 135, 39, 120, 193, 78, 7, 132, + ]; + + let valid = + verify_secp256r1_ecdsa_signature(&hashed_message, &pub_key_x, &pub_key_y, &signature); + + assert!(valid) + } } diff --git a/brillig_vm/Cargo.toml b/brillig_vm/Cargo.toml index b319ddaf0..073d406c4 100644 --- a/brillig_vm/Cargo.toml +++ b/brillig_vm/Cargo.toml @@ -17,6 +17,7 @@ blake2.workspace = true sha2.workspace = true sha3.workspace = true k256.workspace = true +p256.workspace = true [features] default = ["bn254"] diff --git a/brillig_vm/src/black_box.rs b/brillig_vm/src/black_box.rs index 5214b4863..a6e0aaf7a 100644 --- a/brillig_vm/src/black_box.rs +++ b/brillig_vm/src/black_box.rs @@ -2,21 +2,10 @@ use crate::{memory::Memory, opcodes::HeapVector, HeapArray, RegisterIndex, Regis use acir_field::FieldElement; use blake2::digest::generic_array::GenericArray; use blake2::{Blake2s256, Digest}; -use k256::elliptic_curve::sec1::FromEncodedPoint; -use k256::elliptic_curve::PrimeField; use serde::{Deserialize, Serialize}; use sha2::Sha256; use sha3::Keccak256; -use k256::{ecdsa::Signature, Scalar}; -use k256::{ - elliptic_curve::{ - sec1::{Coordinates, ToEncodedPoint}, - IsHigh, - }, - AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, -}; - /// These opcodes provide an equivalent of ACIR blackbox functions. /// They are implemented as native functions in the VM. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] @@ -41,6 +30,14 @@ pub enum BlackBoxOp { signature: HeapArray, result: RegisterIndex, }, + /// Verifies a ECDSA signature over the secp256r1 curve. + EcdsaSecp256r1 { + hashed_msg: HeapVector, + public_key_x: HeapArray, + public_key_y: HeapArray, + signature: HeapArray, + result: RegisterIndex, + }, } impl BlackBoxOp { @@ -64,6 +61,13 @@ impl BlackBoxOp { public_key_y, signature, result: result_register, + } + | BlackBoxOp::EcdsaSecp256r1 { + hashed_msg, + public_key_x, + public_key_y, + signature, + result: result_register, } => { let message_values = memory.read_slice( registers.get(hashed_msg.pointer).to_usize(), @@ -93,12 +97,21 @@ impl BlackBoxOp { .try_into() .expect("Expected a 64-element signature array"); - let result = verify_secp256k1_ecdsa_signature( - &message_bytes, - &public_key_x_bytes, - &public_key_y_bytes, - &signature_bytes, - ); + let result = match self { + BlackBoxOp::EcdsaSecp256k1 { .. } => verify_secp256k1_ecdsa_signature( + &message_bytes, + &public_key_x_bytes, + &public_key_y_bytes, + &signature_bytes, + ), + BlackBoxOp::EcdsaSecp256r1 { .. } => verify_secp256r1_ecdsa_signature( + &message_bytes, + &public_key_x_bytes, + &public_key_y_bytes, + &signature_bytes, + ), + _ => unreachable!(), + }; registers.set(*result_register, (result as u128).into()) } @@ -219,6 +232,74 @@ fn verify_secp256k1_ecdsa_signature( public_key_y_bytes: &[u8; 32], signature: &[u8; 64], ) -> bool { + use k256::elliptic_curve::sec1::FromEncodedPoint; + use k256::elliptic_curve::PrimeField; + + use k256::{ecdsa::Signature, Scalar}; + use k256::{ + elliptic_curve::{ + sec1::{Coordinates, ToEncodedPoint}, + IsHigh, + }, + AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, + }; + // Convert the inputs into k256 data structures + + let signature = Signature::try_from(signature.as_slice()).unwrap(); + + let point = EncodedPoint::from_affine_coordinates( + public_key_x_bytes.into(), + public_key_y_bytes.into(), + true, + ); + let pubkey = PublicKey::from_encoded_point(&point).unwrap(); + + let z = Scalar::from_repr(*GenericArray::from_slice(hashed_msg)).unwrap(); + + // Finished converting bytes into data structures + + let r = signature.r(); + let s = signature.s(); + + // Ensure signature is "low S" normalized ala BIP 0062 + if s.is_high().into() { + return false; + } + + let s_inv = s.invert().unwrap(); + let u1 = z * s_inv; + let u2 = *r * s_inv; + + #[allow(non_snake_case)] + let R: AffinePoint = ((ProjectivePoint::GENERATOR * u1) + + (ProjectivePoint::from(*pubkey.as_affine()) * u2)) + .to_affine(); + + match R.to_encoded_point(false).coordinates() { + Coordinates::Uncompressed { x, y: _ } => Scalar::from_repr(*x).unwrap().eq(&r), + _ => unreachable!("Point is uncompressed"), + } +} + +// TODO(https://github.com/noir-lang/acvm/issues/402): remove from here and use the one from acvm +fn verify_secp256r1_ecdsa_signature( + hashed_msg: &[u8], + public_key_x_bytes: &[u8; 32], + public_key_y_bytes: &[u8; 32], + signature: &[u8; 64], +) -> bool { + use p256::elliptic_curve::sec1::FromEncodedPoint; + use p256::elliptic_curve::PrimeField; + + use p256::{ecdsa::Signature, Scalar}; + use p256::{ + elliptic_curve::{ + sec1::{Coordinates, ToEncodedPoint}, + IsHigh, + }, + AffinePoint, EncodedPoint, ProjectivePoint, PublicKey, + }; + // Convert the inputs into k256 data structures let signature = Signature::try_from(signature.as_slice()).unwrap();