Skip to content

Commit

Permalink
Merge pull request #3 from ABlockOfficial/unwrap_removal
Browse files Browse the repository at this point in the history
Unwrap removal; Bump to v0.1.2
  • Loading branch information
BHouwens authored Feb 7, 2024
2 parents 0541950 + e2e17b1 commit 69222aa
Show file tree
Hide file tree
Showing 7 changed files with 158 additions and 20 deletions.
39 changes: 39 additions & 0 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
## Description
Provide a clear and concise description of the changes introduced in this pull request.

Fixes # (issue number)

## Changelog

- List the changes to the codebase that this PR introduces

## Type of Change
Please mark the appropriate option by putting an "x" inside the brackets:

- [ ] Bug fix
- [ ] New feature
- [ ] Enhancement or optimization
- [ ] Documentation update
- [ ] Other (please specify)

## Checklist
Put an "x" in the boxes that apply. If you're unsure about any of these, don't hesitate to ask. We're here to help!

- [ ] I have tested the changes locally and they work as expected.
- [ ] I have added necessary documentation or updated existing documentation.
- [ ] My code follows the project's coding standards and style guidelines.
- [ ] I have added/updated relevant tests to ensure the changes are properly covered.
- [ ] I have checked for and resolved any merge conflicts.
- [ ] My commits have clear and descriptive messages.

## Screenshots (if applicable)
If the changes affect the UI or have visual effects, please provide screenshots or GIFs showcasing the changes.

## Additional Context (if applicable)
Add any additional context or information about the changes that may be helpful in understanding the pull request.

## Related Issues (if applicable)
If this pull request is related to any existing issues, please list them here.

## Requested Reviewers
Mention any specific individuals or teams you would like to request a review from.
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "valence_core"
version = "0.1.1"
version = "0.1.2"
edition = "2021"
license = "MIT"
keywords = ["blockchain", "L2", "peer-to-peer", "P2P"]
Expand All @@ -24,3 +24,4 @@ serde_json = "1.0.103"
hex = "0.4.3"
cuckoofilter = "0.5.0"
tracing = "0.1.37"
sha3 = "0.10.8"
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Otherwise, add the following to your `Cargo.toml` file:

```toml
[dependencies]
valence_core = "0.1.0"
valence_core = "0.1.2"
```

<p align="left">(<a href="#top">back to top</a>)</p>
Expand Down
2 changes: 1 addition & 1 deletion src/api/responses.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ pub fn json_embed_transaction(value: Vec<u8>) -> JsonReply {

/// Embed serialized JSON into wrapping JSON
pub fn json_serialize_embed<T: Serialize>(value: T) -> JsonReply {
JsonReply::new(serde_json::to_vec(&value).unwrap())
JsonReply::new(serde_json::to_vec(&value).unwrap_or_default())
}

/// Embed JSON into wrapping JSON
Expand Down
107 changes: 97 additions & 10 deletions src/crypto.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
pub use ring;
pub use serde;
use std::convert::TryInto;
use tracing::warn;

pub mod sign_ed25519 {
use super::deserialize_slice;
Expand All @@ -11,6 +11,7 @@ pub mod sign_ed25519 {
pub use ring::signature::{ED25519, ED25519_PUBLIC_KEY_LEN};
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use tracing::warn;

pub type PublicKeyBase = <SecretKey as KeyPair>::PublicKey;

Expand All @@ -29,6 +30,12 @@ pub mod sign_ed25519 {
[u8; ED25519_SIGNATURE_LEN],
);

impl Default for Signature {
fn default() -> Self {
Self([0; ED25519_SIGNATURE_LEN])
}
}

impl Signature {
pub fn from_slice(slice: &[u8]) -> Option<Self> {
Some(Self(slice.try_into().ok()?))
Expand All @@ -50,6 +57,12 @@ pub mod sign_ed25519 {
[u8; ED25519_PUBLIC_KEY_LEN],
);

impl Default for PublicKey {
fn default() -> Self {
Self([0; ED25519_PUBLIC_KEY_LEN])
}
}

impl PublicKey {
pub fn from_slice(slice: &[u8]) -> Option<Self> {
Some(Self(slice.try_into().ok()?))
Expand Down Expand Up @@ -86,14 +99,34 @@ pub mod sign_ed25519 {
}

pub fn sign_detached(msg: &[u8], sk: &SecretKey) -> Signature {
let secret = SecretKeyBase::from_pkcs8(sk.as_ref()).unwrap();
Signature(secret.sign(msg).as_ref().try_into().unwrap())
let secret = match SecretKeyBase::from_pkcs8(sk.as_ref()) {
Ok(secret) => secret,
Err(_) => {
warn!("Invalid secret key");
return Signature([0; ED25519_SIGNATURE_LEN]);
}
};

let signature = match secret.sign(msg).as_ref().try_into() {
Ok(signature) => signature,
Err(_) => {
warn!("Invalid signature");
return Signature([0; ED25519_SIGNATURE_LEN]);
}
};
Signature(signature)
}

pub fn verify_append(sm: &[u8], pk: &PublicKey) -> bool {
if sm.len() > ED25519_SIGNATURE_LEN {
let start = sm.len() - ED25519_SIGNATURE_LEN;
let sig = Signature(sm[start..].try_into().unwrap());
let sig = Signature(match sm[start..].try_into() {
Ok(sig) => sig,
Err(_) => {
warn!("Invalid signature");
return false;
}
});
let msg = &sm[..start];
verify_detached(&sig, msg, pk)
} else {
Expand All @@ -110,10 +143,38 @@ pub mod sign_ed25519 {

pub fn gen_keypair() -> (PublicKey, SecretKey) {
let rand = ring::rand::SystemRandom::new();
let pkcs8 = SecretKeyBase::generate_pkcs8(&rand).unwrap();
let secret = SecretKeyBase::from_pkcs8(pkcs8.as_ref()).unwrap();
let public = PublicKey(secret.public_key().as_ref().try_into().unwrap());
let secret = SecretKey::from_slice(pkcs8.as_ref()).unwrap();
let pkcs8 = match SecretKeyBase::generate_pkcs8(&rand) {
Ok(pkcs8) => pkcs8,
Err(_) => {
warn!("Failed to generate secret key base for pkcs8");
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
}
};

let secret = match SecretKeyBase::from_pkcs8(pkcs8.as_ref()) {
Ok(secret) => secret,
Err(_) => {
warn!("Invalid secret key base");
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
}
};

let pub_key_gen = match secret.public_key().as_ref().try_into() {
Ok(pub_key_gen) => pub_key_gen,
Err(_) => {
warn!("Invalid public key generation");
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
}
};
let public = PublicKey(pub_key_gen);
let secret = match SecretKey::from_slice(pkcs8.as_ref()) {
Some(secret) => secret,
None => {
warn!("Invalid secret key");
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
}
};

(public, secret)
}
}
Expand Down Expand Up @@ -218,6 +279,7 @@ pub mod pbkdf2 {
use serde::{Deserialize, Serialize};
use std::convert::TryInto;
use std::num::NonZeroU32;
use tracing::warn;

pub const SALT_LEN: usize = 256 / 8;
pub const OPSLIMIT_INTERACTIVE: u32 = 100_000;
Expand All @@ -242,7 +304,13 @@ pub mod pbkdf2 {
}

pub fn derive_key(key: &mut [u8], passwd: &[u8], salt: &Salt, iterations: u32) {
let iterations = NonZeroU32::new(iterations).unwrap();
let iterations = match NonZeroU32::new(iterations) {
Some(iterations) => iterations,
None => {
warn!("Invalid iterations in key derivation");
return;
}
};
derive(PBKDF2_HMAC_SHA256, iterations, salt.as_ref(), passwd, key);
}

Expand All @@ -251,6 +319,22 @@ pub mod pbkdf2 {
}
}

pub mod sha3_256 {
pub use sha3::digest::Output;
pub use sha3::Digest;
pub use sha3::Sha3_256;

pub fn digest(data: &[u8]) -> Output<Sha3_256> {
Sha3_256::digest(data)
}

pub fn digest_all<'a>(data: impl Iterator<Item = &'a [u8]>) -> Output<Sha3_256> {
let mut hasher = Sha3_256::new();
data.for_each(|v| hasher.update(v));
hasher.finalize()
}
}

fn deserialize_slice<'de, D: serde::Deserializer<'de>, const N: usize>(
deserializer: D,
) -> Result<[u8; N], D::Error> {
Expand All @@ -265,7 +349,10 @@ pub fn generate_random<const N: usize>() -> [u8; N] {

use ring::rand::SecureRandom;
let rand = ring::rand::SystemRandom::new();
rand.fill(&mut value).unwrap();
match rand.fill(&mut value) {
Ok(_) => (),
Err(_) => warn!("Failed to generate random bytes"),
};

value
}
3 changes: 1 addition & 2 deletions src/db/mongo_db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ impl KvStoreConnection for MongoDbConn {
Ok(document) => document,
Err(e) => {
event!(Level::ERROR, "Failed to serialize data with error: {e}");
panic!("Failed to serialize data with error: {e}");
Document::new()
}
};

Expand All @@ -83,7 +83,6 @@ impl KvStoreConnection for MongoDbConn {
Ok(_) => (),
Err(e) => {
event!(Level::ERROR, "Failed to set data with error: {e}");
panic!("Failed to set data with error: {e}");
}
};

Expand Down
22 changes: 17 additions & 5 deletions src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::crypto::sign_ed25519 as sign;
use crate::crypto::sign_ed25519::{PublicKey, Signature};
use serde::{Deserialize, Serialize};
use tracing::warn;

/// Function to validate the signature using Ed25519
///
Expand All @@ -17,24 +18,35 @@ pub fn validate_signature(public_key: &str, msg: &str, signature: &str) -> bool
return false;
}

let pk = PublicKey::from_slice(&pk_decode.unwrap());
let signature = Signature::from_slice(&sig_decode.unwrap());
let pk = PublicKey::from_slice(&pk_decode.unwrap_or_default());
let signature = Signature::from_slice(&sig_decode.unwrap_or_default());

if pk.is_none() || signature.is_none() {
warn!("Failed to decode public key or signature");
return false;
}

sign::verify_detached(&signature.unwrap(), msg.as_bytes(), &pk.unwrap())
sign::verify_detached(
&signature.unwrap_or_default(),
msg.as_bytes(),
&pk.unwrap_or_default(),
)
}

/// Function to serialize data
pub fn serialize_data<T: Serialize>(data: &T) -> String {
serde_json::to_string(data).unwrap()
serde_json::to_string(data).unwrap_or_default()
}

/// Function to deserialize data
pub fn deserialize_data<T: for<'a> Deserialize<'a>>(data: String) -> T {
serde_json::from_str(&data).unwrap()
match serde_json::from_str(&data) {
Ok(result) => result,
Err(_) => {
warn!("Failed to deserialize data");
serde_json::from_str("{}").unwrap()
}
}
}

#[cfg(test)]
Expand Down

0 comments on commit 69222aa

Please sign in to comment.