Skip to content

Commit

Permalink
Address clippy lints for libwallet
Browse files Browse the repository at this point in the history
  • Loading branch information
olanod committed Jun 14, 2024
1 parent 9767fa5 commit 5d311b4
Show file tree
Hide file tree
Showing 10 changed files with 55 additions and 54 deletions.
16 changes: 16 additions & 0 deletions .github/workflows/libwallet-pr.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
on:
pull_request:
paths: ['libwallet/**']

name: Libwallet

jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: extractions/setup-just@v2
- name: Check
run: just -f libwallet/justfile check
- name: Lint
run: just -f libwallet/justfile lint
1 change: 1 addition & 0 deletions libwallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ serde_json = {version = "1.0", default-features = false, features = ["alloc"]}
dirs = "4.0"

[features]
default = ["substrate"]
# default = ["std", "substrate", "vault_simple", "mnemonic", "rand", "vault_pass", "vault_os", "util_pin"]
rand = ["rand_core", "schnorrkel?/getrandom"]
sr25519 = ["dep:schnorrkel"]
Expand Down
1 change: 0 additions & 1 deletion libwallet/justfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ default:

check:
cargo check

lint:
cargo clippy -- -D warnings

Expand Down
8 changes: 2 additions & 6 deletions libwallet/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
use core::fmt::{Debug, Display};
use crate::{Public, Signer};

use crate::{
Public, Signer,
};

pub trait Account: Signer + Display {
pub trait Account: Signer + core::fmt::Display {
fn public(&self) -> impl Public;
}
26 changes: 15 additions & 11 deletions libwallet/src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,19 @@ impl<const N: usize> Signature for Bytes<N> {}
/// Something that can sign messages
pub trait Signer {
type Signature: Signature;
async fn sign_msg(&self, data: impl AsRef<[u8]>) -> Result<Self::Signature, ()>;
async fn verify(&self, msg: impl AsRef<[u8]>, sig: impl AsRef<[u8]>) -> bool;
fn sign_msg(
&self,
data: impl AsRef<[u8]>,
) -> impl core::future::Future<Output = Result<Self::Signature, ()>>;

fn verify(
&self,
msg: impl AsRef<[u8]>,
sig: impl AsRef<[u8]>,
) -> impl core::future::Future<Output = bool>;
}
/// Wrappers to represent any supported key pair.
pub mod any {
use crate::Signer;

use super::{Public, Signature};
use core::fmt;

Expand Down Expand Up @@ -227,7 +233,7 @@ pub mod sr25519 {
super::derive::parse_substrate_junctions(path)
.fold(self.secret.clone(), |key, (part, hard)| {
if hard {
key.hard_derive_mini_secret_key(Some(ChainCode(part)), &[])
key.hard_derive_mini_secret_key(Some(ChainCode(part)), [])
.0
.expand(ExpansionMode::Ed25519)
} else {
Expand Down Expand Up @@ -323,8 +329,6 @@ pub mod sr25519 {
}

mod derive {
use core::convert::identity;

use super::Bytes;

/// Something to derive key pairs form
Expand All @@ -342,8 +346,8 @@ mod derive {
pub(super) fn parse_substrate_junctions(
path: &str,
) -> impl Iterator<Item = (Junction, bool)> + '_ {
path.split_inclusive("/")
.flat_map(|s| if s == "/" { "" } else { s }.split("/")) // "//Alice//Bob" -> ["","","Alice","","","Bob"]
path.split_inclusive('/')
.flat_map(|s| if s == "/" { "" } else { s }.split('/')) // "//Alice//Bob" -> ["","","Alice","","","Bob"]
.scan(0u8, |j, part| {
Some(if part.is_empty() {
*j += 1;
Expand All @@ -354,7 +358,7 @@ mod derive {
Some((encoded_junction(part), hard))
})
})
.filter_map(identity)
.flatten()
}

fn encoded_junction(part: &str) -> Junction {
Expand All @@ -364,7 +368,7 @@ mod derive {
} else {
let len = part.len().min(JUNCTION_LEN - 1);
code[0] = (len as u8) << 2;
code[1..len + 1].copy_from_slice(&part[..len].as_bytes());
code[1..len + 1].copy_from_slice(part[..len].as_bytes());
}
code
}
Expand Down
11 changes: 2 additions & 9 deletions libwallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@ mod substrate_ext;

pub use account::Account;
use arrayvec::ArrayVec;
use core::{cell::RefCell, convert::TryInto, fmt};
use key_pair::any::AnySignature;
use core::{convert::TryInto, fmt};

#[cfg(feature = "mnemonic")]
use mnemonic;
Expand All @@ -28,7 +27,6 @@ pub use mnemonic::{Language, Mnemonic};
pub use vault::Vault;
pub mod vault;


const MSG_MAX_SIZE: usize = u8::MAX as usize;
type Message = ArrayVec<u8, { MSG_MAX_SIZE }>;

Expand Down Expand Up @@ -95,11 +93,7 @@ where
) -> Result<(), Error<V::Error>> {
if self.is_locked() {
let vault = &mut self.vault;

let signer = vault
.unlock(account, cred)
.await
.map_err(|e| Error::Vault(e))?;
let signer = vault.unlock(account, cred).await.map_err(Error::Vault)?;

if self.default_account.is_none() {
self.default_account = Some(0);
Expand Down Expand Up @@ -292,4 +286,3 @@ impl<V> From<mnemonic::Error> for Error<V> {
Error::InvalidPhrase
}
}

2 changes: 0 additions & 2 deletions libwallet/src/substrate_ext.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::Network;

trait SubstrateExt {}

impl From<&str> for Network {
fn from(s: &str) -> Self {
// TODO use registry
Expand Down
12 changes: 6 additions & 6 deletions libwallet/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use core::{iter, ops};
use crate::Pair;

#[cfg(feature = "rand")]
pub fn random_bytes<R, const S: usize>(rng: &mut R) -> [u8; S]
Expand Down Expand Up @@ -38,11 +37,8 @@ macro_rules! seed_from_entropy {
};
}

use arrayvec::ArrayString;
pub(crate) use seed_from_entropy;

use crate::{any::{self, AnySignature}, Network, Public };

impl Pin {
const LEN: usize = 4;

Expand All @@ -63,7 +59,11 @@ impl Pin {
let mut seed = [0; S];
// using same hashing strategy as Substrate to have some compatibility
// when pin is 0(no pin) we produce the same addresses
let len = self.eq(&0).then_some(salt.len() - 2).unwrap_or(salt.len());
let len = if self.eq(&0) {
salt.len() - 2
} else {
salt.len()
};
pbkdf2::<Hmac<Sha512>>(data, &salt[..len], 2048, &mut seed);
seed
}
Expand All @@ -81,7 +81,7 @@ impl<'a> From<&'a str> for Pin {
.map(|c| c.to_digit(16).unwrap_or(0))
.enumerate()
.fold(0, |pin, (i, d)| {
pin | ((d as u16) << (Pin::LEN - 1 - i) * Pin::LEN)
pin | ((d as u16) << ((Pin::LEN - 1 - i) * Pin::LEN))
}))
}
}
Expand Down
20 changes: 9 additions & 11 deletions libwallet/src/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,18 @@ pub trait Vault {
type Id;
type Account: Account;

async fn unlock(
fn unlock(
&mut self,
account: Self::Id,
cred: impl Into<Self::Credentials>,
) -> Result<Self::Account, Self::Error>;
) -> impl core::future::Future<Output = Result<Self::Account, Self::Error>>;
}

mod utils {
const MAX_PATH_LEN: usize = 16;
use arrayvec::ArrayString;

use crate::{account::Account, any::AnySignature, any, Derive, Network, Pair, Public};

use crate::{account::Account, any, any::AnySignature, Derive, Network, Pair, Public};

/// The root account is a container of the key pairs stored in the vault and cannot be
/// used to sign messages directly, we always derive new key pairs from it to create
Expand Down Expand Up @@ -82,7 +81,7 @@ mod utils {
path: ArrayString<MAX_PATH_LEN>,
name: ArrayString<{ MAX_PATH_LEN - 2 }>,
}

impl Account for AccountSigner {
fn public(&self) -> impl Public {
self.pair.as_ref().expect("account unlocked").public()
Expand All @@ -91,13 +90,13 @@ mod utils {

impl AccountSigner {
pub(crate) fn new<'a>(name: impl Into<Option<&'a str>>) -> Self {
let n = name.into().unwrap_or_else(|| "default");
let n = name.into().unwrap_or("default");
let mut path = ArrayString::from("//").unwrap();
path.push_str(&n);
path.push_str(n);
AccountSigner {
pair: None,
network: Network::default(),
name: ArrayString::from(&n).expect("short name"),
name: ArrayString::from(n).expect("short name"),
path,
}
}
Expand Down Expand Up @@ -133,12 +132,11 @@ mod utils {
type Signature = AnySignature;

async fn sign_msg(&self, msg: impl AsRef<[u8]>) -> Result<Self::Signature, ()> {
Ok(self
.pair
self.pair
.as_ref()
.expect("account unlocked")
.sign_msg(msg)
.await?)
.await
}

async fn verify(&self, msg: impl AsRef<[u8]>, sig: impl AsRef<[u8]>) -> bool {
Expand Down
12 changes: 4 additions & 8 deletions libwallet/src/vault/simple.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
use core::convert::TryInto;
use core::marker::PhantomData;

use arrayvec::ArrayVec;

use crate::util::{seed_from_entropy, Pin};
use crate::{
vault::utils::{AccountSigner, RootAccount},
Derive, Vault,
Vault,
};
use core::marker::PhantomData;

/// A vault that holds secrets in memory
pub struct Simple<S> {
locked: Option<[u8; 32]>,
unlocked: Option<[u8; 32]>,
_phantom: PhantomData<S>
_phantom: PhantomData<S>,
}

impl<S> Simple<S> {
Expand All @@ -37,7 +33,7 @@ impl<S> Simple<S> {
Simple {
locked: Some(crate::util::random_bytes::<_, 32>(rng)),
unlocked: None,
_phantom: Default::default()
_phantom: Default::default(),
}
}

Expand Down

0 comments on commit 5d311b4

Please sign in to comment.