Skip to content

Commit 69222aa

Browse files
authored
Merge pull request #3 from ABlockOfficial/unwrap_removal
Unwrap removal; Bump to v0.1.2
2 parents 0541950 + e2e17b1 commit 69222aa

File tree

7 files changed

+158
-20
lines changed

7 files changed

+158
-20
lines changed

.github/pull_request_template.md

+39
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## Description
2+
Provide a clear and concise description of the changes introduced in this pull request.
3+
4+
Fixes # (issue number)
5+
6+
## Changelog
7+
8+
- List the changes to the codebase that this PR introduces
9+
10+
## Type of Change
11+
Please mark the appropriate option by putting an "x" inside the brackets:
12+
13+
- [ ] Bug fix
14+
- [ ] New feature
15+
- [ ] Enhancement or optimization
16+
- [ ] Documentation update
17+
- [ ] Other (please specify)
18+
19+
## Checklist
20+
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!
21+
22+
- [ ] I have tested the changes locally and they work as expected.
23+
- [ ] I have added necessary documentation or updated existing documentation.
24+
- [ ] My code follows the project's coding standards and style guidelines.
25+
- [ ] I have added/updated relevant tests to ensure the changes are properly covered.
26+
- [ ] I have checked for and resolved any merge conflicts.
27+
- [ ] My commits have clear and descriptive messages.
28+
29+
## Screenshots (if applicable)
30+
If the changes affect the UI or have visual effects, please provide screenshots or GIFs showcasing the changes.
31+
32+
## Additional Context (if applicable)
33+
Add any additional context or information about the changes that may be helpful in understanding the pull request.
34+
35+
## Related Issues (if applicable)
36+
If this pull request is related to any existing issues, please list them here.
37+
38+
## Requested Reviewers
39+
Mention any specific individuals or teams you would like to request a review from.

Cargo.toml

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "valence_core"
3-
version = "0.1.1"
3+
version = "0.1.2"
44
edition = "2021"
55
license = "MIT"
66
keywords = ["blockchain", "L2", "peer-to-peer", "P2P"]
@@ -24,3 +24,4 @@ serde_json = "1.0.103"
2424
hex = "0.4.3"
2525
cuckoofilter = "0.5.0"
2626
tracing = "0.1.37"
27+
sha3 = "0.10.8"

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ Otherwise, add the following to your `Cargo.toml` file:
6060

6161
```toml
6262
[dependencies]
63-
valence_core = "0.1.0"
63+
valence_core = "0.1.2"
6464
```
6565

6666
<p align="left">(<a href="#top">back to top</a>)</p>

src/api/responses.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ pub fn json_embed_transaction(value: Vec<u8>) -> JsonReply {
4949

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

5555
/// Embed JSON into wrapping JSON

src/crypto.rs

+97-10
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
pub use ring;
2-
pub use serde;
32
use std::convert::TryInto;
3+
use tracing::warn;
44

55
pub mod sign_ed25519 {
66
use super::deserialize_slice;
@@ -11,6 +11,7 @@ pub mod sign_ed25519 {
1111
pub use ring::signature::{ED25519, ED25519_PUBLIC_KEY_LEN};
1212
use serde::{Deserialize, Serialize};
1313
use std::convert::TryInto;
14+
use tracing::warn;
1415

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

@@ -29,6 +30,12 @@ pub mod sign_ed25519 {
2930
[u8; ED25519_SIGNATURE_LEN],
3031
);
3132

33+
impl Default for Signature {
34+
fn default() -> Self {
35+
Self([0; ED25519_SIGNATURE_LEN])
36+
}
37+
}
38+
3239
impl Signature {
3340
pub fn from_slice(slice: &[u8]) -> Option<Self> {
3441
Some(Self(slice.try_into().ok()?))
@@ -50,6 +57,12 @@ pub mod sign_ed25519 {
5057
[u8; ED25519_PUBLIC_KEY_LEN],
5158
);
5259

60+
impl Default for PublicKey {
61+
fn default() -> Self {
62+
Self([0; ED25519_PUBLIC_KEY_LEN])
63+
}
64+
}
65+
5366
impl PublicKey {
5467
pub fn from_slice(slice: &[u8]) -> Option<Self> {
5568
Some(Self(slice.try_into().ok()?))
@@ -86,14 +99,34 @@ pub mod sign_ed25519 {
8699
}
87100

88101
pub fn sign_detached(msg: &[u8], sk: &SecretKey) -> Signature {
89-
let secret = SecretKeyBase::from_pkcs8(sk.as_ref()).unwrap();
90-
Signature(secret.sign(msg).as_ref().try_into().unwrap())
102+
let secret = match SecretKeyBase::from_pkcs8(sk.as_ref()) {
103+
Ok(secret) => secret,
104+
Err(_) => {
105+
warn!("Invalid secret key");
106+
return Signature([0; ED25519_SIGNATURE_LEN]);
107+
}
108+
};
109+
110+
let signature = match secret.sign(msg).as_ref().try_into() {
111+
Ok(signature) => signature,
112+
Err(_) => {
113+
warn!("Invalid signature");
114+
return Signature([0; ED25519_SIGNATURE_LEN]);
115+
}
116+
};
117+
Signature(signature)
91118
}
92119

93120
pub fn verify_append(sm: &[u8], pk: &PublicKey) -> bool {
94121
if sm.len() > ED25519_SIGNATURE_LEN {
95122
let start = sm.len() - ED25519_SIGNATURE_LEN;
96-
let sig = Signature(sm[start..].try_into().unwrap());
123+
let sig = Signature(match sm[start..].try_into() {
124+
Ok(sig) => sig,
125+
Err(_) => {
126+
warn!("Invalid signature");
127+
return false;
128+
}
129+
});
97130
let msg = &sm[..start];
98131
verify_detached(&sig, msg, pk)
99132
} else {
@@ -110,10 +143,38 @@ pub mod sign_ed25519 {
110143

111144
pub fn gen_keypair() -> (PublicKey, SecretKey) {
112145
let rand = ring::rand::SystemRandom::new();
113-
let pkcs8 = SecretKeyBase::generate_pkcs8(&rand).unwrap();
114-
let secret = SecretKeyBase::from_pkcs8(pkcs8.as_ref()).unwrap();
115-
let public = PublicKey(secret.public_key().as_ref().try_into().unwrap());
116-
let secret = SecretKey::from_slice(pkcs8.as_ref()).unwrap();
146+
let pkcs8 = match SecretKeyBase::generate_pkcs8(&rand) {
147+
Ok(pkcs8) => pkcs8,
148+
Err(_) => {
149+
warn!("Failed to generate secret key base for pkcs8");
150+
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
151+
}
152+
};
153+
154+
let secret = match SecretKeyBase::from_pkcs8(pkcs8.as_ref()) {
155+
Ok(secret) => secret,
156+
Err(_) => {
157+
warn!("Invalid secret key base");
158+
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
159+
}
160+
};
161+
162+
let pub_key_gen = match secret.public_key().as_ref().try_into() {
163+
Ok(pub_key_gen) => pub_key_gen,
164+
Err(_) => {
165+
warn!("Invalid public key generation");
166+
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
167+
}
168+
};
169+
let public = PublicKey(pub_key_gen);
170+
let secret = match SecretKey::from_slice(pkcs8.as_ref()) {
171+
Some(secret) => secret,
172+
None => {
173+
warn!("Invalid secret key");
174+
return (PublicKey([0; ED25519_PUBLIC_KEY_LEN]), SecretKey(vec![]));
175+
}
176+
};
177+
117178
(public, secret)
118179
}
119180
}
@@ -218,6 +279,7 @@ pub mod pbkdf2 {
218279
use serde::{Deserialize, Serialize};
219280
use std::convert::TryInto;
220281
use std::num::NonZeroU32;
282+
use tracing::warn;
221283

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

244306
pub fn derive_key(key: &mut [u8], passwd: &[u8], salt: &Salt, iterations: u32) {
245-
let iterations = NonZeroU32::new(iterations).unwrap();
307+
let iterations = match NonZeroU32::new(iterations) {
308+
Some(iterations) => iterations,
309+
None => {
310+
warn!("Invalid iterations in key derivation");
311+
return;
312+
}
313+
};
246314
derive(PBKDF2_HMAC_SHA256, iterations, salt.as_ref(), passwd, key);
247315
}
248316

@@ -251,6 +319,22 @@ pub mod pbkdf2 {
251319
}
252320
}
253321

322+
pub mod sha3_256 {
323+
pub use sha3::digest::Output;
324+
pub use sha3::Digest;
325+
pub use sha3::Sha3_256;
326+
327+
pub fn digest(data: &[u8]) -> Output<Sha3_256> {
328+
Sha3_256::digest(data)
329+
}
330+
331+
pub fn digest_all<'a>(data: impl Iterator<Item = &'a [u8]>) -> Output<Sha3_256> {
332+
let mut hasher = Sha3_256::new();
333+
data.for_each(|v| hasher.update(v));
334+
hasher.finalize()
335+
}
336+
}
337+
254338
fn deserialize_slice<'de, D: serde::Deserializer<'de>, const N: usize>(
255339
deserializer: D,
256340
) -> Result<[u8; N], D::Error> {
@@ -265,7 +349,10 @@ pub fn generate_random<const N: usize>() -> [u8; N] {
265349

266350
use ring::rand::SecureRandom;
267351
let rand = ring::rand::SystemRandom::new();
268-
rand.fill(&mut value).unwrap();
352+
match rand.fill(&mut value) {
353+
Ok(_) => (),
354+
Err(_) => warn!("Failed to generate random bytes"),
355+
};
269356

270357
value
271358
}

src/db/mongo_db.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl KvStoreConnection for MongoDbConn {
6565
Ok(document) => document,
6666
Err(e) => {
6767
event!(Level::ERROR, "Failed to serialize data with error: {e}");
68-
panic!("Failed to serialize data with error: {e}");
68+
Document::new()
6969
}
7070
};
7171

@@ -83,7 +83,6 @@ impl KvStoreConnection for MongoDbConn {
8383
Ok(_) => (),
8484
Err(e) => {
8585
event!(Level::ERROR, "Failed to set data with error: {e}");
86-
panic!("Failed to set data with error: {e}");
8786
}
8887
};
8988

src/utils.rs

+17-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::crypto::sign_ed25519 as sign;
22
use crate::crypto::sign_ed25519::{PublicKey, Signature};
33
use serde::{Deserialize, Serialize};
4+
use tracing::warn;
45

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

20-
let pk = PublicKey::from_slice(&pk_decode.unwrap());
21-
let signature = Signature::from_slice(&sig_decode.unwrap());
21+
let pk = PublicKey::from_slice(&pk_decode.unwrap_or_default());
22+
let signature = Signature::from_slice(&sig_decode.unwrap_or_default());
2223

2324
if pk.is_none() || signature.is_none() {
25+
warn!("Failed to decode public key or signature");
2426
return false;
2527
}
2628

27-
sign::verify_detached(&signature.unwrap(), msg.as_bytes(), &pk.unwrap())
29+
sign::verify_detached(
30+
&signature.unwrap_or_default(),
31+
msg.as_bytes(),
32+
&pk.unwrap_or_default(),
33+
)
2834
}
2935

3036
/// Function to serialize data
3137
pub fn serialize_data<T: Serialize>(data: &T) -> String {
32-
serde_json::to_string(data).unwrap()
38+
serde_json::to_string(data).unwrap_or_default()
3339
}
3440

3541
/// Function to deserialize data
3642
pub fn deserialize_data<T: for<'a> Deserialize<'a>>(data: String) -> T {
37-
serde_json::from_str(&data).unwrap()
43+
match serde_json::from_str(&data) {
44+
Ok(result) => result,
45+
Err(_) => {
46+
warn!("Failed to deserialize data");
47+
serde_json::from_str("{}").unwrap()
48+
}
49+
}
3850
}
3951

4052
#[cfg(test)]

0 commit comments

Comments
 (0)