Skip to content

Commit

Permalink
crypto: Add r1 verify and verify_recoverable to Move API
Browse files Browse the repository at this point in the history
  • Loading branch information
joyqvq committed Jan 30, 2023
1 parent 00e2275 commit b10895f
Show file tree
Hide file tree
Showing 6 changed files with 420 additions and 1 deletion.
136 changes: 136 additions & 0 deletions crates/sui-framework/docs/ecdsa_r1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@

<a name="0x2_ecdsa_r1"></a>

# Module `0x2::ecdsa_r1`



- [Constants](#@Constants_0)
- [Function `ecrecover`](#0x2_ecdsa_r1_ecrecover)
- [Function `secp256r1_verify`](#0x2_ecdsa_r1_secp256r1_verify)
- [Function `secp256r1_verify_recoverable`](#0x2_ecdsa_r1_secp256r1_verify_recoverable)


<pre><code></code></pre>



<a name="@Constants_0"></a>

## Constants


<a name="0x2_ecdsa_r1_EFailToRecoverPubKey"></a>

Error if the public key cannot be recovered from the signature.


<pre><code><b>const</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_EFailToRecoverPubKey">EFailToRecoverPubKey</a>: u64 = 0;
</code></pre>



<a name="0x2_ecdsa_r1_EInvalidSignature"></a>

Error if the signature is invalid.


<pre><code><b>const</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_EInvalidSignature">EInvalidSignature</a>: u64 = 1;
</code></pre>



<a name="0x2_ecdsa_r1_ecrecover"></a>

## Function `ecrecover`

@param signature: A 65-bytes signature in form (r, s, v) that is signed using
Secp256r1. Reference implementation on signature generation using RFC6979:
https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs
The accepted v values are {0, 1, 2, 3}.

@param hashed_msg: the hashed 32-bytes message. The message must be hashed instead
of plain text to be secure.

If the signature is valid, return the corresponding recovered Secpk256r1 public
key, otherwise throw error. This is similar to ecrecover in Ethereum, can only be
applied to Secp256r1 signatures.


<pre><code><b>public</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_ecrecover">ecrecover</a>(signature: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): <a href="">vector</a>&lt;u8&gt;
</code></pre>



<details>
<summary>Implementation</summary>


<pre><code><b>public</b> <b>native</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_ecrecover">ecrecover</a>(signature: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): <a href="">vector</a>&lt;u8&gt;;
</code></pre>



</details>

<a name="0x2_ecdsa_r1_secp256r1_verify"></a>

## Function `secp256r1_verify`

@param signature: A 64-bytes signature in form (r, s) that is signed using
Secp256r1. This is an non-recoverable signature without recovery id.
Reference implementation on signature generation using RFC6979:
https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs

@param public_key: The public key to verify the signature against
@param hashed_msg: The hashed 32-bytes message, same as what the signature is signed against.

If the signature is valid to the pubkey and hashed message, return true. Else false.


<pre><code><b>public</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_secp256r1_verify">secp256r1_verify</a>(signature: &<a href="">vector</a>&lt;u8&gt;, public_key: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): bool
</code></pre>



<details>
<summary>Implementation</summary>


<pre><code><b>public</b> <b>native</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_secp256r1_verify">secp256r1_verify</a>(signature: &<a href="">vector</a>&lt;u8&gt;, public_key: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): bool;
</code></pre>



</details>

<a name="0x2_ecdsa_r1_secp256r1_verify_recoverable"></a>

## Function `secp256r1_verify_recoverable`

@param signature: A 65-bytes signature in form (r, s, v) that is signed using
Secp256r1. This is an recoverable signature with recovery id denoted as v.
Reference implementation on signature generation using RFC6979:
https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/recoverable.rs#L35

@param public_key: The public key to verify the signature against
@param hashed_msg: The hashed 32-bytes message, same as what the signature is signed against.

If the signature is valid to the pubkey and hashed message, return true. Else false.


<pre><code><b>public</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_secp256r1_verify_recoverable">secp256r1_verify_recoverable</a>(signature: &<a href="">vector</a>&lt;u8&gt;, public_key: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): bool
</code></pre>



<details>
<summary>Implementation</summary>


<pre><code><b>public</b> <b>native</b> <b>fun</b> <a href="ecdsa_r1.md#0x2_ecdsa_r1_secp256r1_verify_recoverable">secp256r1_verify_recoverable</a>(signature: &<a href="">vector</a>&lt;u8&gt;, public_key: &<a href="">vector</a>&lt;u8&gt;, msg: &<a href="">vector</a>&lt;u8&gt;): bool;
</code></pre>



</details>
46 changes: 46 additions & 0 deletions crates/sui-framework/sources/crypto/ecdsa_r1.move
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

module sui::ecdsa_r1 {

/// Error if the public key cannot be recovered from the signature.
const EFailToRecoverPubKey: u64 = 0;

/// Error if the signature is invalid.
const EInvalidSignature: u64 = 1;

/// @param signature: A 65-bytes signature in form (r, s, v) that is signed using
/// Secp256r1. Reference implementation on signature generation using RFC6979:
/// https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs
/// The accepted v values are {0, 1, 2, 3}.
///
/// @param hashed_msg: the hashed 32-bytes message. The message must be hashed instead
/// of plain text to be secure.
///
/// If the signature is valid, return the corresponding recovered Secpk256r1 public
/// key, otherwise throw error. This is similar to ecrecover in Ethereum, can only be
/// applied to Secp256r1 signatures.
public native fun ecrecover(signature: &vector<u8>, msg: &vector<u8>): vector<u8>;

/// @param signature: A 64-bytes signature in form (r, s) that is signed using
/// Secp256r1. This is an non-recoverable signature without recovery id.
/// Reference implementation on signature generation using RFC6979:
/// https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/mod.rs
///
/// @param public_key: The public key to verify the signature against
/// @param hashed_msg: The hashed 32-bytes message, same as what the signature is signed against.
///
/// If the signature is valid to the pubkey and hashed message, return true. Else false.
public native fun secp256r1_verify(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool;

/// @param signature: A 65-bytes signature in form (r, s, v) that is signed using
/// Secp256r1. This is an recoverable signature with recovery id denoted as v.
/// Reference implementation on signature generation using RFC6979:
/// https://github.com/MystenLabs/fastcrypto/blob/74aec4886e62122a5b769464c2bea5f803cf8ecc/fastcrypto/src/secp256r1/recoverable.rs#L35
///
/// @param public_key: The public key to verify the signature against
/// @param hashed_msg: The hashed 32-bytes message, same as what the signature is signed against.
///
/// If the signature is valid to the pubkey and hashed message, return true. Else false.
public native fun secp256r1_verify_recoverable(signature: &vector<u8>, public_key: &vector<u8>, msg: &vector<u8>): bool;
}
134 changes: 134 additions & 0 deletions crates/sui-framework/src/natives/crypto/ecdsa_r1.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
use crate::legacy_empty_cost;
use fastcrypto::secp256r1::Secp256r1Signature;
use fastcrypto::{
secp256r1::{
recoverable::{Secp256r1RecoverablePublicKey, Secp256r1RecoverableSignature},
Secp256r1PublicKey,
},
traits::ToFromBytes,
Verifier,
};
use move_binary_format::errors::PartialVMResult;
use move_vm_runtime::native_functions::NativeContext;
use move_vm_types::{
loaded_data::runtime_types::Type,
natives::function::NativeResult,
pop_arg,
values::{Value, VectorRef},
};
use smallvec::smallvec;
use std::collections::VecDeque;
use sui_types::error::SuiError;

pub const FAIL_TO_RECOVER_PUBKEY: u64 = 0;
pub const INVALID_SIGNATURE: u64 = 1;

pub fn ecrecover(
_context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(ty_args.is_empty());
debug_assert!(args.len() == 2);

let msg = pop_arg!(args, VectorRef);
let signature = pop_arg!(args, VectorRef);

let msg_ref = msg.as_bytes_ref();
let signature_ref = signature.as_bytes_ref();

// TODO: implement native gas cost estimation https://github.com/MystenLabs/sui/issues/3593
let cost = legacy_empty_cost();
match recover_pubkey(&signature_ref, &msg_ref) {
Ok(pubkey) => Ok(NativeResult::ok(
cost,
smallvec![Value::vector_u8(pubkey.as_bytes().to_vec())],
)),
Err(SuiError::InvalidSignature { error: _ }) => {
Ok(NativeResult::err(cost, INVALID_SIGNATURE))
}
Err(_) => Ok(NativeResult::err(cost, FAIL_TO_RECOVER_PUBKEY)),
}
}

fn recover_pubkey(signature: &[u8], msg: &[u8]) -> Result<Secp256r1RecoverablePublicKey, SuiError> {
match <Secp256r1RecoverableSignature as ToFromBytes>::from_bytes(signature) {
Ok(signature) => match signature.recover(msg) {
Ok(pubkey) => Ok(pubkey),
Err(e) => Err(SuiError::KeyConversionError(e.to_string())),
},
Err(e) => Err(SuiError::InvalidSignature {
error: e.to_string(),
}),
}
}

pub fn secp256r1_verify(
_context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(ty_args.is_empty());
debug_assert!(args.len() == 3);

let hashed_msg = pop_arg!(args, VectorRef);
let public_key_bytes = pop_arg!(args, VectorRef);
let signature_bytes = pop_arg!(args, VectorRef);

let hashed_msg_ref = hashed_msg.as_bytes_ref();
let public_key_bytes_ref = public_key_bytes.as_bytes_ref();
let signature_bytes_ref = signature_bytes.as_bytes_ref();

// TODO: implement native gas cost estimation https://github.com/MystenLabs/sui/issues/4086
let cost = legacy_empty_cost();

let signature = match <Secp256r1Signature as ToFromBytes>::from_bytes(&signature_bytes_ref) {
Ok(signature) => signature,
Err(_) => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
};

let public_key = match <Secp256r1PublicKey as ToFromBytes>::from_bytes(&public_key_bytes_ref) {
Ok(public_key) => public_key,
Err(_) => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
};

let result = public_key.verify(&hashed_msg_ref, &signature).is_ok();
Ok(NativeResult::ok(cost, smallvec![Value::bool(result)]))
}

pub fn secp256r1_verify_recoverable(
_context: &mut NativeContext,
ty_args: Vec<Type>,
mut args: VecDeque<Value>,
) -> PartialVMResult<NativeResult> {
debug_assert!(ty_args.is_empty());
debug_assert!(args.len() == 3);

let hashed_msg = pop_arg!(args, VectorRef);
let public_key_bytes = pop_arg!(args, VectorRef);
let signature_bytes = pop_arg!(args, VectorRef);

let hashed_msg_ref = hashed_msg.as_bytes_ref();
let public_key_bytes_ref = public_key_bytes.as_bytes_ref();
let signature_bytes_ref = signature_bytes.as_bytes_ref();

// TODO: implement native gas cost estimation https://github.com/MystenLabs/sui/issues/4086
let cost = legacy_empty_cost();

let signature =
match <Secp256r1RecoverableSignature as ToFromBytes>::from_bytes(&signature_bytes_ref) {
Ok(signature) => signature,
Err(_) => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
};

let public_key =
match <Secp256r1RecoverablePublicKey as ToFromBytes>::from_bytes(&public_key_bytes_ref) {
Ok(public_key) => public_key,
Err(_) => return Ok(NativeResult::ok(cost, smallvec![Value::bool(false)])),
};

let result = public_key.verify(&hashed_msg_ref, &signature).is_ok();
Ok(NativeResult::ok(cost, smallvec![Value::bool(result)]))
}
1 change: 1 addition & 0 deletions crates/sui-framework/src/natives/crypto/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
pub mod bls12381;
pub mod bulletproofs;
pub mod ecdsa_k1;
pub mod ecdsa_r1;
pub mod ed25519;
pub mod elliptic_curve;
pub mod groth16;
Expand Down
13 changes: 12 additions & 1 deletion crates/sui-framework/src/natives/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use move_vm_types::{
use std::sync::Arc;

use self::crypto::{
bls12381, bulletproofs, ecdsa_k1, ed25519, elliptic_curve, groth16, hmac, tbls,
bls12381, bulletproofs, ecdsa_k1, ecdsa_r1, ed25519, elliptic_curve, groth16, hmac, tbls,
};

pub fn all_natives(
Expand Down Expand Up @@ -102,6 +102,17 @@ pub fn all_natives(
"secp256k1_verify_recoverable",
make_native!(ecdsa_k1::secp256k1_verify_recoverable),
),
("ecdsa_r1", "ecrecover", make_native!(ecdsa_r1::ecrecover)),
(
"ecdsa_r1",
"secp256r1_verify",
make_native!(ecdsa_r1::secp256r1_verify),
),
(
"ecdsa_r1",
"secp256r1_verify_recoverable",
make_native!(ecdsa_r1::secp256r1_verify_recoverable),
),
(
"ed25519",
"ed25519_verify",
Expand Down
Loading

0 comments on commit b10895f

Please sign in to comment.