Skip to content

Commit

Permalink
chore: add the MIT License to project
Browse files Browse the repository at this point in the history
  • Loading branch information
ai-chen2050 authored and fshif committed Sep 20, 2024
1 parent 076430b commit 418af51
Show file tree
Hide file tree
Showing 12 changed files with 83 additions and 63 deletions.
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 hetu

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 18 additions & 15 deletions crates/crypto/src/recovery.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use anyhow::Ok;
use hex::FromHex;
use rand::rngs::OsRng;
use secp256k1::ecdsa::{RecoverableSignature, RecoveryId};
use sha3::{Digest, Keccak256};

pub fn public_key_to_address(public_key_hex: &str) -> String {
let public_key_bytes = hex::decode(public_key_hex).expect("Invalid hex string");
pub fn public_key_to_address(public_key_hex: &str) -> anyhow::Result<String, anyhow::Error> {
let public_key_bytes = hex::decode(public_key_hex)?;

let mut hasher = Keccak256::new();
hasher.update(&public_key_bytes[1..]);
Expand All @@ -16,7 +17,7 @@ pub fn public_key_to_address(public_key_hex: &str) -> String {
let mut address = "0x".to_owned();
address.push_str(&hex::encode(address_bytes));

address
Ok(address)
}

pub fn gen_secp256k1_keypair() -> (String, String) {
Expand All @@ -31,18 +32,19 @@ pub fn sign_message_recover_pk(
secp: &secp256k1::Secp256k1<secp256k1::All>,
secret_key: &secp256k1::SecretKey,
message: &[u8],
) -> RecoverableSignature {
let message = secp256k1::Message::from_digest_slice(message).expect("32-byte message");
secp.sign_ecdsa_recoverable(&message, &secret_key)
) -> anyhow::Result<RecoverableSignature, anyhow::Error> {
let message = secp256k1::Message::from_digest_slice(message)?;
Ok(secp.sign_ecdsa_recoverable(&message, &secret_key))
}

pub fn recover_public_key(
secp: &secp256k1::Secp256k1<secp256k1::All>,
signature: &RecoverableSignature,
message: &[u8],
) -> Option<secp256k1::PublicKey> {
let message = secp256k1::Message::from_digest_slice(message).expect("32-byte message");
secp.recover_ecdsa(&message, &signature).ok()
) -> anyhow::Result<secp256k1::PublicKey, anyhow::Error> {
let message = secp256k1::Message::from_digest_slice(message)?;
let pub_key = secp.recover_ecdsa(&message, &signature)?;
Ok(pub_key)
}

pub fn verify_secp256k1_recovery_pk(
Expand All @@ -69,16 +71,17 @@ pub fn verify_secp256k1_recovery_pk(
pub fn verify_secp256k1_recovery_pk_bytes(
signature_bytes: Vec<u8>,
message_bytes: [u8; 32],
) -> Option<secp256k1::PublicKey> {
) -> anyhow::Result<secp256k1::PublicKey, anyhow::Error> {

let secp = secp256k1::Secp256k1::new();

let recovery_id = RecoveryId::from_i32(i32::from(signature_bytes[64])).unwrap();
let recovery_id = RecoveryId::from_i32(i32::from(signature_bytes[64]))?;
let signatures_no_id = &signature_bytes[0..64];

let recoverable_signature = RecoverableSignature::from_compact(signatures_no_id, recovery_id).unwrap();
let message = secp256k1::Message::from_digest_slice(&message_bytes).unwrap();
secp.recover_ecdsa(&message, &recoverable_signature).ok()
let recoverable_signature = RecoverableSignature::from_compact(signatures_no_id, recovery_id)?;
let message = secp256k1::Message::from_digest_slice(&message_bytes)?;
let pub_key = secp.recover_ecdsa(&message, &recoverable_signature)?;
Ok(pub_key)
}

#[cfg(test)]
Expand All @@ -100,7 +103,7 @@ mod tests {

let message = "Hello, Ethereum!".to_owned();
let msg = message.sha256().to_fixed_bytes();
let signature_recover = sign_message_recover_pk(&secp, &secret_key, &msg);
let signature_recover = sign_message_recover_pk(&secp, &secret_key, &msg).unwrap();
let serialized_signature = signature_recover.serialize_compact();
println!("sig struct: {:?}", serialized_signature);

Expand Down
14 changes: 8 additions & 6 deletions crates/enclaves/src/nitro_secure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub type HandleFn = Arc<
dyn Fn(
Vec<u8>,
Arc<NitroSecureModule>,
[Vec<u8>; 3],
Arc<[Vec<u8>; 3]>,
UnboundedSender<Vec<u8>>,
) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + Send>>
+ Send
Expand Down Expand Up @@ -40,13 +40,14 @@ impl NitroSecureModule {
..
} = &mut request
else {
unreachable!()
anyhow::bail!("user_data is None in Attestation request");
};

buf.extend(user_data);
match aws_nitro_enclaves_nsm_api::driver::nsm_process_request(self.0, request) {
aws_nitro_enclaves_nsm_api::api::Response::Attestation { document } => Ok(document),
aws_nitro_enclaves_nsm_api::api::Response::Error(err) => anyhow::bail!("{err:?}"),
_ => anyhow::bail!("unimplemented"),
response => anyhow::bail!("Unexpected response: {:?}", response),
}
}

Expand All @@ -56,7 +57,7 @@ impl NitroSecureModule {
{
aws_nitro_enclaves_nsm_api::api::Response::DescribePCR { lock: _, data } => Ok(data),
aws_nitro_enclaves_nsm_api::api::Response::Error(err) => anyhow::bail!("{err:?}"),
_ => anyhow::bail!("unimplemented"),
response => anyhow::bail!("Unexpected response: {:?}", response),
}
}

Expand All @@ -72,11 +73,11 @@ impl NitroSecureModule {
};

let nsm = std::sync::Arc::new(Self::new()?);
let pcrs = [
let pcrs = Arc::new([
nsm.describe_pcr(0)?,
nsm.describe_pcr(1)?,
nsm.describe_pcr(2)?,
];
]);

let socket_fd = socket(
AddressFamily::Vsock,
Expand Down Expand Up @@ -133,6 +134,7 @@ impl NitroSecureModule {
});
}
});
// this loop keeps one connect, and still works when meets some error in only connect.
loop {
let result = tokio::select! {
result = &mut read_session, if !read_session.is_finished() => result,
Expand Down
6 changes: 3 additions & 3 deletions crates/vlc/src/ordinary_clock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ mod tests {
let mut count = 0;

// sign once
let signature_recover = sign_message_recover_pk(&secp, &secret_key, &clock.sha256().to_fixed_bytes());
let signature_recover = sign_message_recover_pk(&secp, &secret_key, &clock.sha256().to_fixed_bytes()).unwrap();

let start_time = Instant::now();
let close_loops_session = async {
Expand Down Expand Up @@ -337,7 +337,7 @@ mod tests {

#[tokio::test]
#[ignore]
async fn stress_sig_verify_update() -> anyhow::Result<()> {
async fn stress_signature_verify_update() -> anyhow::Result<()> {
use DigestHash as _;

let secp = secp256k1::Secp256k1::new();
Expand Down Expand Up @@ -371,7 +371,7 @@ mod tests {

// sign
let signature_recover = sign_message_recover_pk(&secp, &secret_key, &current_clock.sha256().to_fixed_bytes());
signatures = Some(signature_recover);
signatures = Some(signature_recover.unwrap());
}
anyhow::Ok(())
};
Expand Down
1 change: 1 addition & 0 deletions crates/vrf/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ curve25519-dalek = "4.1.3"
derive_deref = "1.0.2"
anyhow = { version = "1.0.79", features = ["backtrace"] }
failure = "0.1.3"
thiserror = "1.0.63"
ed25519-dalek = { version = "2.1.1", features = ["serde", "digest", "rand_core", "pem", "pkcs8"] }
hex = "0.4.3"
lazy_static = "1.3.0"
Expand Down
5 changes: 2 additions & 3 deletions crates/vrf/src/ecvrf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
//! let output: Output = (&proof).into();
//! ```
use failure::bail;
use crate::traits::*;
use core::convert::TryFrom;
use curve25519_dalek::{
Expand Down Expand Up @@ -173,7 +172,7 @@ impl TryFrom<&[u8]> for VRFPublicKey {
impl VRFPublicKey {
/// Given a [`Proof`] and an input, returns whether or not the proof is valid for the input
/// and public key
pub fn verify(&self, proof: &Proof, alpha: &[u8]) -> Result<(), failure::Error> {
pub fn verify(&self, proof: &Proof, alpha: &[u8]) -> Result<(), anyhow::Error> {
let h_point = self.hash_to_curve(alpha);
let pk_point = CompressedEdwardsY::from_slice(self.as_bytes())
.unwrap()
Expand All @@ -189,7 +188,7 @@ impl VRFPublicKey {
if proof.c == cprime {
Ok(())
} else {
bail!("The proof failed to verify for this public key")
anyhow::bail!("The proof failed to verify for this public key")
}
}

Expand Down
4 changes: 2 additions & 2 deletions crates/vrf/src/sample.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ impl Sampler {
}
}

pub fn hex_to_biguint(&self, hex_str: &str) -> BigUint {
pub fn hex_to_biguint(hex_str: &str) -> BigUint {
BigUint::from_str_radix(hex_str, 16).expect("Invalid hex string")
}

Expand All @@ -38,7 +38,7 @@ mod tests {
fn meets() {
let sampler = Sampler::new(512);
let vrf_output_hex = "a64c292ec45f6b252828aff9a02a0fe88d2fcc7f5fc61bb328f03f4c6c0657a9d26efb23b87647ff54f71cd51a6fa4c4e31661d8f72b41ff00ac4d2eec2ea7b3";
let vrf_output = sampler.hex_to_biguint(vrf_output_hex);
let vrf_output = Sampler::hex_to_biguint(vrf_output_hex);

let target_probability = 0.1;
let threshold = sampler.calculate_threshold(target_probability);
Expand Down
23 changes: 12 additions & 11 deletions crates/vrf/src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
//! For examples on how to use these traits, see the implementations of the [`ed25519`] or
//! [`bls12381`] modules.
use std::fmt;
use core::convert::{From, TryFrom};
use proptest_derive::Arbitrary;
use serde::{Deserialize, Serialize};
Expand All @@ -26,25 +27,25 @@ impl AsRef<[u8; 32]> for HashValue {
/// (often, due to mangled material or curve equation failure for ECC) and
/// validation errors (material recognizable but unacceptable for use,
/// e.g. unsafe).
#[derive(Clone, Debug, PartialEq, Eq, failure::Fail)]
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum CryptoMaterialError {
/// Key or signature material does not deserialize correctly.
#[fail(display = "DeserializationError")]
#[error("DeserializationError")]
DeserializationError,
/// Key or signature material deserializes, but is otherwise not valid.
#[fail(display = "ValidationError")]
#[error("ValidationError")]
ValidationError,
/// Key or signature material does not have the expected size.
#[fail(display = "WrongLengthError")]
#[error("WrongLengthError")]
WrongLengthError,
/// Part of the signature or key is not canonical resulting to malleability issues.
#[fail(display = "CanonicalRepresentationError")]
#[error("CanonicalRepresentationError")]
CanonicalRepresentationError,
/// A curve point (i.e., a public key) lies on a small group.
#[fail(display = "SmallSubgroupError")]
#[error("SmallSubgroupError")]
SmallSubgroupError,
/// A curve point (i.e., a public key) does not satisfy the curve equation.
#[fail(display = "PointNotOnCurveError")]
#[error("PointNotOnCurveError")]
PointNotOnCurveError,
}

Expand Down Expand Up @@ -89,7 +90,7 @@ pub trait ValidKeyStringExt: ValidKey {
.and_then(|ref bytes| Self::try_from(bytes))
}
/// A function to encode into hex-string after serializing.
fn to_encoded_string(&self) -> Result<String, failure::Error> {
fn to_encoded_string(&self) -> Result<String, fmt::Error> {
Ok(::hex::encode(&self.to_bytes()))
}
}
Expand Down Expand Up @@ -164,7 +165,7 @@ pub trait VerifyingKey:
&self,
message: &HashValue,
signature: &Self::SignatureMaterial,
) -> Result<(), failure::Error> {
) -> Result<(), anyhow::Error> {
signature.verify(message, self)
}
}
Expand All @@ -188,14 +189,14 @@ pub trait Signature:
type VerifyingKeyMaterial: VerifyingKey<SignatureMaterial = Self>;

/// The verification function.
fn verify(&self, message: &HashValue, public_key: &Self::VerifyingKeyMaterial) -> Result<(), failure::Error>;
fn verify(&self, message: &HashValue, public_key: &Self::VerifyingKeyMaterial) -> Result<(), anyhow::Error>;

/// Native verification function.
fn verify_arbitrary_msg(
&self,
message: &[u8],
public_key: &Self::VerifyingKeyMaterial,
) -> Result<(), failure::Error>;
) -> Result<(), anyhow::Error>;

/// Convert the signature into a byte representation.
fn to_bytes(&self) -> Vec<u8>;
Expand Down
4 changes: 0 additions & 4 deletions crates/vrf/src/unit_tests/vrf_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,6 @@ fn gen_keypair_prove_and_verify() {
fn test_expand_secret_key() {
for tv in TESTVECTORS.iter() {
let sk = from_string!(VRFPrivateKey, tv.SK);
println!("{:?}", sk);
let esk = VRFExpandedPrivateKey::from(&sk);
let pk = VRFPublicKey::try_from(&sk).unwrap();
assert_eq!(tv.PK, to_string!(pk));
Expand Down Expand Up @@ -148,9 +147,6 @@ fn test_hash_points() {
let s_scalar = k_scalar + c_scalar * sk.key;
let s_scalar = ed25519_Scalar::from_bytes_mod_order(s_scalar.to_bytes());

let mut c_bytes = [0u8; 16];
c_bytes.copy_from_slice(&c_scalar.to_bytes()[..16]);

let pi = Proof::new(gamma, c_scalar, s_scalar);

assert_eq!(tv.pi, to_string!(pi));
Expand Down
2 changes: 1 addition & 1 deletion demos/tee_vlc/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ This module verifiable logic clock is an implementation of Chronos's TEE backend

## Prepare environment

Now, this repository use the aws nitro enclave as its trust execution environment.
Now, this repository uses the aws nitro enclave as its trust execution environment.

So, please create a cloud virtual instance and notice choose the `Amazon-2023 linux` as base image.
Because this base operator system is more friendly for using of the aws nitro enclave.
Expand Down
Loading

0 comments on commit 418af51

Please sign in to comment.