Skip to content

Commit

Permalink
Cargo fmt + fix clippy and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
iKapitonau committed Dec 11, 2024
1 parent ef91e07 commit 9aec7a9
Show file tree
Hide file tree
Showing 12 changed files with 87 additions and 109 deletions.
10 changes: 3 additions & 7 deletions packages/crypto/src/hkdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ pub fn hkdf_sha_256(
let okm = zero_bytes.as_mut_slice();
match hk.expand(info, okm) {
Ok(_) => Ok(okm.to_vec()),
Err(e) => {
Err(StdError::generic_err(format!("{:?}", e)))
}
Err(e) => Err(StdError::generic_err(format!("{:?}", e))),
}
}

Expand All @@ -33,8 +31,6 @@ pub fn hkdf_sha_512(
let okm = zero_bytes.as_mut_slice();
match hk.expand(info, okm) {
Ok(_) => Ok(okm.to_vec()),
Err(e) => {
Err(StdError::generic_err(format!("{:?}", e)))
}
Err(e) => Err(StdError::generic_err(format!("{:?}", e))),
}
}
}
1 change: 0 additions & 1 deletion packages/crypto/src/rng.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ pub struct ContractPrng {
}

impl ContractPrng {

pub fn from_env(env: &Env) -> Self {
let seed = env.block.random.as_ref().unwrap();

Expand Down
4 changes: 2 additions & 2 deletions packages/notification/Readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Each notification channel will have a specified data format, which is defined by

The following example illustrates how you might implement this for a channel called `my_channel` and notification data containing two fields: `sender` and `amount`.

```rust
```ignore
use cosmwasm_std::{Api, StdError, StdResult};
use secret_toolkit::notification::{EncoderExt, CBL_ARRAY_SHORT, CBL_BIGNUM_U64, CBL_U8, Notification, DirectChannel, GroupChannel};
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -48,7 +48,7 @@ To send a notification to a recipient you first create a new `Notification` stru

The following code snippet creates a notification for the above `my_channel` and adds it to the contract `Response` as a plaintext attribute.

```rust
```ignore
let notification = Notification::new(
recipient,
MyNotification {
Expand Down
109 changes: 50 additions & 59 deletions packages/notification/src/cbor.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cosmwasm_std::{CanonicalAddr, StdResult, StdError};
use cosmwasm_std::{CanonicalAddr, StdError, StdResult};
use minicbor::{data as cbor_data, encode as cbor_encode, Encoder};

/// Length of encoding an arry header that holds less than 24 items
Expand Down Expand Up @@ -35,68 +35,59 @@ pub const CBL_TIMESTAMP: usize = 1 + 1 + 8;
pub const CBL_ADDRESS: usize = 1 + 20;

/// Wraps the CBOR error to CosmWasm StdError
pub fn cbor_to_std_error<T>(e: cbor_encode::Error<T>) -> StdError {
StdError::generic_err("CBOR encoding error")
pub fn cbor_to_std_error<T>(_e: cbor_encode::Error<T>) -> StdError {
StdError::generic_err("CBOR encoding error")
}

/// Extends the minicbor encoder with wrapper functions that handle CBOR errors
pub trait EncoderExt {
fn ext_tag(&mut self, tag: cbor_data::IanaTag) -> StdResult<&mut Self>;

fn ext_u8(&mut self, value: u8) -> StdResult<&mut Self>;
fn ext_u32(&mut self, value: u32) -> StdResult<&mut Self>;
fn ext_u64_from_u128(&mut self, value: u128) -> StdResult<&mut Self>;
fn ext_address(&mut self, value: CanonicalAddr) -> StdResult<&mut Self>;
fn ext_bytes(&mut self, value: &[u8]) -> StdResult<&mut Self>;
fn ext_timestamp(&mut self, value: u64) -> StdResult<&mut Self>;
fn ext_tag(&mut self, tag: cbor_data::IanaTag) -> StdResult<&mut Self>;

fn ext_u8(&mut self, value: u8) -> StdResult<&mut Self>;
fn ext_u32(&mut self, value: u32) -> StdResult<&mut Self>;
fn ext_u64_from_u128(&mut self, value: u128) -> StdResult<&mut Self>;
fn ext_address(&mut self, value: CanonicalAddr) -> StdResult<&mut Self>;
fn ext_bytes(&mut self, value: &[u8]) -> StdResult<&mut Self>;
fn ext_timestamp(&mut self, value: u64) -> StdResult<&mut Self>;
}

impl<T: cbor_encode::Write> EncoderExt for Encoder<T> {
#[inline]
fn ext_tag(&mut self, tag: cbor_data::IanaTag) -> StdResult<&mut Self> {
self
.tag(cbor_data::Tag::from(tag))
.map_err(cbor_to_std_error)
}

#[inline]
fn ext_u8(&mut self, value: u8) -> StdResult<&mut Self> {
self
.u8(value)
.map_err(cbor_to_std_error)
}

#[inline]
fn ext_u32(&mut self, value: u32) -> StdResult<&mut Self> {
self
.u32(value)
.map_err(cbor_to_std_error)
}

#[inline]
fn ext_u64_from_u128(&mut self, value: u128) -> StdResult<&mut Self> {
self
.ext_tag(cbor_data::IanaTag::PosBignum)?
.ext_bytes(&value.to_be_bytes()[8..])
}

#[inline]
fn ext_address(&mut self, value: CanonicalAddr) -> StdResult<&mut Self> {
self.ext_bytes(&value.as_slice())
}

#[inline]
fn ext_bytes(&mut self, value: &[u8]) -> StdResult<&mut Self> {
self
.bytes(&value)
.map_err(cbor_to_std_error)
}

#[inline]
fn ext_timestamp(&mut self, value: u64) -> StdResult<&mut Self> {
self
.ext_tag(cbor_data::IanaTag::Timestamp)?
.u64(value)
.map_err(cbor_to_std_error)
}
}
#[inline]
fn ext_tag(&mut self, tag: cbor_data::IanaTag) -> StdResult<&mut Self> {
self.tag(cbor_data::Tag::from(tag))
.map_err(cbor_to_std_error)
}

#[inline]
fn ext_u8(&mut self, value: u8) -> StdResult<&mut Self> {
self.u8(value).map_err(cbor_to_std_error)
}

#[inline]
fn ext_u32(&mut self, value: u32) -> StdResult<&mut Self> {
self.u32(value).map_err(cbor_to_std_error)
}

#[inline]
fn ext_u64_from_u128(&mut self, value: u128) -> StdResult<&mut Self> {
self.ext_tag(cbor_data::IanaTag::PosBignum)?
.ext_bytes(&value.to_be_bytes()[8..])
}

#[inline]
fn ext_address(&mut self, value: CanonicalAddr) -> StdResult<&mut Self> {
self.ext_bytes(value.as_slice())
}

#[inline]
fn ext_bytes(&mut self, value: &[u8]) -> StdResult<&mut Self> {
self.bytes(value).map_err(cbor_to_std_error)
}

#[inline]
fn ext_timestamp(&mut self, value: u64) -> StdResult<&mut Self> {
self.ext_tag(cbor_data::IanaTag::Timestamp)?
.u64(value)
.map_err(cbor_to_std_error)
}
}
23 changes: 11 additions & 12 deletions packages/notification/src/funcs.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::cipher_data;
use cosmwasm_std::{Binary, CanonicalAddr, StdResult};
use secret_toolkit_crypto::{sha_256, hkdf_sha_256, HmacSha256};
use hkdf::hmac::Mac;
use crate::cipher_data;
use secret_toolkit_crypto::{hkdf_sha_256, sha_256, HmacSha256};

pub const SEED_LEN: usize = 32; // 256 bits

Expand All @@ -10,9 +10,14 @@ pub const SEED_LEN: usize = 32; // 256 bits
///
/// Returns a notification id for the given address and channel id.
///
pub fn notification_id(seed: &Binary, channel: &str, tx_hash: &String) -> StdResult<Binary> {
pub fn notification_id(seed: &Binary, channel: &str, tx_hash: &str) -> StdResult<Binary> {
// compute notification ID for this event
let material = [channel.as_bytes(), ":".as_bytes(), tx_hash.to_ascii_uppercase().as_bytes()].concat();
let material = [
channel.as_bytes(),
":".as_bytes(),
tx_hash.to_ascii_uppercase().as_bytes(),
]
.concat();

// create HMAC from seed
let mut mac: HmacSha256 = HmacSha256::new_from_slice(seed.0.as_slice()).unwrap();
Expand All @@ -27,7 +32,7 @@ pub fn notification_id(seed: &Binary, channel: &str, tx_hash: &String) -> StdRes
///
/// fn encrypt_notification_data
///
/// Returns encrypted bytes given plaintext bytes, address, and channel id.
/// Returns encrypted bytes given plaintext bytes, address, and channel id.
/// Optionally, can set block size (default 36).
///
pub fn encrypt_notification_data(
Expand Down Expand Up @@ -73,12 +78,7 @@ pub fn encrypt_notification_data(

/// get the seed for a secret and given address
pub fn get_seed(addr: &CanonicalAddr, secret: &[u8]) -> StdResult<Binary> {
let seed = hkdf_sha_256(
&None,
secret,
addr.as_slice(),
SEED_LEN,
)?;
let seed = hkdf_sha_256(&None, secret, addr.as_slice(), SEED_LEN)?;

Ok(Binary::from(seed))
}
Expand All @@ -96,4 +96,3 @@ fn zero_pad_right(message: &mut Vec<u8>, block_size: usize) -> &mut Vec<u8> {
message.extend(std::iter::repeat(0x00).take(missing));
message
}

12 changes: 6 additions & 6 deletions packages/notification/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#![doc = include_str!("../Readme.md")]

pub mod structs;
pub mod funcs;
pub mod cipher;
pub mod cbor;
pub use structs::*;
pub use funcs::*;
pub use cipher::*;
pub mod cipher;
pub mod funcs;
pub mod structs;
pub use cbor::*;
pub use cipher::*;
pub use funcs::*;
pub use structs::*;
19 changes: 8 additions & 11 deletions packages/notification/src/structs.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
use cosmwasm_std::{Addr, Api, Binary, Env, StdError, StdResult, Uint64};
use minicbor::Encoder;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use minicbor::{encode as cbor_encode, Encoder};

use crate::{encrypt_notification_data, get_seed, notification_id, cbor_to_std_error};
use crate::{cbor_to_std_error, encrypt_notification_data, get_seed, notification_id};

#[derive(Serialize, Debug, Deserialize, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
Expand Down Expand Up @@ -49,7 +49,6 @@ pub trait DirectChannel {
fn encode_cbor(&self, api: &dyn Api, encoder: &mut Encoder<&mut [u8]>) -> StdResult<()>;
}


impl<T: DirectChannel> Notification<T> {
pub fn new(notification_for: Addr, data: T) -> Self {
Notification {
Expand All @@ -66,9 +65,12 @@ impl<T: DirectChannel> Notification<T> {
block_size: Option<usize>,
) -> StdResult<TxHashNotification> {
// extract and normalize tx hash
let tx_hash = env.transaction.clone()
let tx_hash = env
.transaction
.clone()
.ok_or(StdError::generic_err("no tx hash found"))?
.hash.to_ascii_uppercase();
.hash
.to_ascii_uppercase();

// canonicalize notification recipient address
let notification_for_raw = api.addr_canonicalize(self.notification_for.as_str())?;
Expand All @@ -93,14 +95,10 @@ impl<T: DirectChannel> Notification<T> {
)?;

// enstruct
Ok(TxHashNotification {
id,
encrypted_data,
})
Ok(TxHashNotification { id, encrypted_data })
}
}


#[derive(Serialize, Debug, Deserialize, Clone)]
#[cfg_attr(test, derive(Eq, PartialEq))]
pub struct TxHashNotification {
Expand Down Expand Up @@ -190,4 +188,3 @@ pub trait GroupChannel<D: DirectChannel> {

fn notifications(&self) -> &Vec<Notification<D>>;
}

2 changes: 1 addition & 1 deletion packages/serialization/src/base64.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ impl<S: Serde, T> Base64TVisitor<S, T> {
}
}

impl<'de, S: Serde, T: for<'des> de::Deserialize<'des>> de::Visitor<'de> for Base64TVisitor<S, T> {
impl<S: Serde, T: for<'des> de::Deserialize<'des>> de::Visitor<'_> for Base64TVisitor<S, T> {
type Value = Base64Of<S, T>;

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
Expand Down
4 changes: 1 addition & 3 deletions packages/snip20/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,9 +211,7 @@ impl QueryMsg {
code_hash,
msg,
}))
.map_err(|err| {
StdError::generic_err(format!("Error performing {self} query: {err}"))
})
.map_err(|err| StdError::generic_err(format!("Error performing {self} query: {err}")))
}
}

Expand Down
4 changes: 2 additions & 2 deletions packages/snip721/src/expiration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,14 +61,14 @@ mod test {
height: 1000,
time: Timestamp::from_seconds(1000000),
chain_id: "test".to_string(),
random: None
random: None,
};

let block_h2000_t2000000 = BlockInfo {
height: 2000,
time: Timestamp::from_seconds(2000000),
chain_id: "test".to_string(),
random: None
random: None,
};
let exp_h1000 = Expiration::AtHeight(1000);
let exp_t1000000 = Expiration::AtTime(1000000);
Expand Down
4 changes: 1 addition & 3 deletions packages/snip721/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,9 +468,7 @@ impl QueryMsg {
code_hash,
msg,
}))
.map_err(|err| {
StdError::generic_err(format!("Error performing {self} query: {err}"))
})
.map_err(|err| StdError::generic_err(format!("Error performing {self} query: {err}")))
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
pub use secret_toolkit_crypto as crypto;
#[cfg(feature = "incubator")]
pub use secret_toolkit_incubator as incubator;
#[cfg(feature = "notification")]
pub use secret_toolkit_notification as notification;
#[cfg(feature = "permit")]
pub use secret_toolkit_permit as permit;
#[cfg(feature = "serialization")]
Expand All @@ -18,5 +20,3 @@ pub use secret_toolkit_storage as storage;
pub use secret_toolkit_utils as utils;
#[cfg(feature = "viewing-key")]
pub use secret_toolkit_viewing_key as viewing_key;
#[cfg(feature = "notification")]
pub use secret_toolkit_notification as notification;

0 comments on commit 9aec7a9

Please sign in to comment.