Skip to content
This repository has been archived by the owner on Apr 9, 2024. It is now read-only.

Commit

Permalink
feat(acir)!: add EcdsaSecp256r1 blackbox function (#408)
Browse files Browse the repository at this point in the history
Co-authored-by: Kevaundray Wedderburn <kevtheappdev@gmail.com>
  • Loading branch information
Maddiaa0 and kevaundray authored Jul 7, 2023
1 parent faefbbe commit 9895817
Show file tree
Hide file tree
Showing 8 changed files with 308 additions and 32 deletions.
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
] }
4 changes: 4 additions & 0 deletions acir/src/circuit/black_box_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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<BlackBoxFunc> {
Expand All @@ -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),
Expand Down
37 changes: 36 additions & 1 deletion acir/src/circuit/opcodes/black_box_function_call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ pub enum BlackBoxFuncCall {
hashed_message: Vec<FunctionInput>,
output: Witness,
},
EcdsaSecp256r1 {
public_key_x: Vec<FunctionInput>,
public_key_y: Vec<FunctionInput>,
signature: Vec<FunctionInput>,
hashed_message: Vec<FunctionInput>,
output: Witness,
},
FixedBaseScalarMul {
input: FunctionInput,
outputs: (Witness, Witness),
Expand Down Expand Up @@ -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)),
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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![],
Expand Down
2 changes: 2 additions & 0 deletions acvm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
19 changes: 18 additions & 1 deletion acvm/src/pwg/blackbox/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
///
Expand Down Expand Up @@ -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)
}
Expand Down
155 changes: 142 additions & 13 deletions acvm/src/pwg/blackbox/signature/ecdsa.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -65,13 +54,121 @@ 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<OpcodeResolution, OpcodeResolutionError> {
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],
public_key_x_bytes: &[u8; 32],
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();
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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)
}
}
1 change: 1 addition & 0 deletions brillig_vm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ blake2.workspace = true
sha2.workspace = true
sha3.workspace = true
k256.workspace = true
p256.workspace = true

[features]
default = ["bn254"]
Expand Down
Loading

0 comments on commit 9895817

Please sign in to comment.