Skip to content

Commit

Permalink
refactor: Update type definition in account_generation.rs and key_pai…
Browse files Browse the repository at this point in the history
…r.rs to use Generic type for Simple vault. Update Vault implementation in simple.rs to use Generic type for Simple vault
  • Loading branch information
S0c5 committed Apr 25, 2024
1 parent ad5cb5c commit 60e6635
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 29 deletions.
2 changes: 1 addition & 1 deletion libwallet/examples/account_generation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use libwallet::{self, vault};
use std::env;

type Wallet = libwallet::Wallet<vault::Simple>;
type Wallet = libwallet::Wallet<vault::Simple<String>>;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand Down
8 changes: 5 additions & 3 deletions libwallet/src/key_pair.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use core::fmt::Debug;
use core::{convert::TryFrom, fmt::Debug};

pub use derive::Derive;

Expand All @@ -25,13 +25,14 @@ impl<const N: usize> Signature for Bytes<N> {}

/// Something that can sign messages
pub trait Signer {
type Signature: Signature + Into<AnySignature>;
type Signature: Signature;
async fn sign_msg<M: AsRef<[u8]>>(&self, data: M) -> Result<Self::Signature, ()>;
async fn verify<M: AsRef<[u8]>>(&self, msg: M, sig: &[u8]) -> 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 @@ -145,6 +146,7 @@ pub mod any {
#[cfg(not(feature = "sr25519"))]
_None,
}

impl AsRef<[u8]> for AnySignature {
fn as_ref(&self) -> &[u8] {
match self {
Expand Down
33 changes: 19 additions & 14 deletions libwallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub mod util;
#[cfg(feature = "substrate")]
mod substrate_ext;

use account::Account;
use arrayvec::ArrayVec;
use core::{cell::RefCell, convert::TryInto, fmt};
use key_pair::any::AnySignature;
Expand All @@ -27,6 +28,7 @@ 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 @@ -73,9 +75,10 @@ where
/// ```
/// # use libwallet::{Wallet, Error, vault, Vault};
/// # use std::convert::TryInto;
/// # type Result = std::result::Result<(), Error<<vault::Simple as Vault>::Error>>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), Error<<SimpleVault as Vault>::Error>>;
/// # #[async_std::main] async fn main() -> Result {
/// # let vault = vault::Simple::generate(&mut rand_core::OsRng);
/// # let vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let mut wallet: Wallet<_> = Wallet::new(vault);
/// if wallet.is_locked() {
/// wallet.unlock(None, None).await?;
Expand Down Expand Up @@ -119,9 +122,10 @@ where
///
/// ```
/// # use libwallet::{Wallet, vault, Error, Signer, Vault};
/// # type Result = std::result::Result<(), Error<<vault::Simple as Vault>::Error>>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), Error<<SimpleVault as Vault>::Error>>;
/// # #[async_std::main] async fn main() -> Result {
/// # let vault = vault::Simple::generate(&mut rand_core::OsRng);
/// # let vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let mut wallet: Wallet<_> = Wallet::new(vault);
/// wallet.unlock(None, None).await?;
///
Expand All @@ -145,9 +149,10 @@ where
///
/// ```
/// # use libwallet::{Wallet, vault, Error, Vault};
/// # type Result = std::result::Result<(), Error<<vault::Simple as Vault>::Error>>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), Error<<SimpleVault as Vault>::Error>>;
/// # #[async_std::main] async fn main() -> Result {
/// # let vault = vault::Simple::generate(&mut rand_core::OsRng);
/// # let vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let mut wallet: Wallet<_> = Wallet::new(vault);
/// wallet.sign_later(&[0x01, 0x02, 0x03]);
///
Expand All @@ -169,9 +174,10 @@ where
///
/// ```
/// # use libwallet::{Wallet, vault, Error, Vault};
/// # type Result = std::result::Result<(), Error<<vault::Simple as Vault>::Error>>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), Error<<SimpleVault as Vault>::Error>>;
/// # #[async_std::main] async fn main() -> Result {
/// # let vault = vault::Simple::generate(&mut rand_core::OsRng);
/// # let vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let mut wallet: Wallet<_> = Wallet::new(vault);
/// wallet.unlock(None, None).await?;
///
Expand All @@ -183,28 +189,27 @@ where
/// assert_eq!(wallet.pending().count(), 0);
/// # Ok(()) }
/// ```
pub async fn sign_pending(&mut self) -> Result<ArrayVec<AnySignature, M>, ()> {
pub async fn sign_pending(&mut self) -> Result<ArrayVec<impl AsRef<[u8]>, M>, ()> {
let mut signatures = ArrayVec::new();
for (msg, a) in self.pending_sign.take() {
let signer = a
.map(|idx| self.account(idx))
.unwrap_or_else(|| self.default_signer().expect("Signer not set"));

let message = signer.sign_msg(&msg).await?.into();

let message = signer.sign_msg(&msg).await?;
signatures.push(message);
}

Ok(signatures)
}

/// Iteratate over the messages pending for signature for all the accounts.
///
/// ```
/// # use libwallet::{Wallet, vault, Error, Vault};
/// # type Result = std::result::Result<(), Error<<vault::Simple as Vault>::Error>>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), Error<<SimpleVault as Vault>::Error>>;
/// # #[async_std::main] async fn main() -> Result {
/// # let vault = vault::Simple::generate(&mut rand_core::OsRng);
/// # let vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let mut wallet: Wallet<_> = Wallet::new(vault);
/// wallet.sign_later(&[0x01]);
/// wallet.sign_later(&[0x02]);
Expand Down
27 changes: 16 additions & 11 deletions libwallet/src/vault/simple.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use core::convert::TryInto;
use core::marker::PhantomData;

use arrayvec::ArrayVec;

Expand All @@ -9,19 +10,21 @@ use crate::{
};

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

impl Simple {
impl<S> Simple<S> {
/// A vault with a random seed, once dropped the the vault can't be restored
///
/// ```
/// # use libwallet::{vault, Error, Derive, Pair, Vault};
/// # type Result = std::result::Result<(), <vault::Simple as Vault>::Error>;
/// # type SimpleVault = vault::Simple<String>;
/// # type Result = std::result::Result<(), <SimpleVault as Vault>::Error>;
/// # #[async_std::main] async fn main() -> Result {
/// let mut vault = vault::Simple::generate(&mut rand_core::OsRng);
/// let mut vault = SimpleVault::generate(&mut rand_core::OsRng);
/// let root = vault.unlock(None, None).await?;
/// # Ok(())
/// }
Expand All @@ -34,6 +37,7 @@ impl Simple {
Simple {
locked: Some(crate::util::random_bytes::<_, 32>(rng)),
unlocked: None,
_phantom: Default::default()
}
}

Expand Down Expand Up @@ -62,6 +66,7 @@ impl Simple {
Simple {
locked: Some(entropy),
unlocked: None,
_phantom: Default::default(),
}
}

Expand All @@ -86,10 +91,10 @@ impl core::fmt::Display for Error {
#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl Vault for Simple {
impl<S: AsRef<str>> Vault for Simple<S> {
type Credentials = Option<Pin>;
type Error = Error;
type Id = Option<ArrayVec<u8, 10>>;
type Id = Option<S>;
type Account = AccountSigner;

async fn unlock(
Expand All @@ -100,11 +105,11 @@ impl Vault for Simple {
self.unlocked = self.locked.take();
let pin = creds.into();
let root_account = self.get_key(pin.unwrap_or_default())?;
let path = path.as_ref().map(|r| {
core::str::from_utf8(r.as_slice())
.expect("it must be a valid utf8 string")
});

// let path = path.as_ref().map(|r| {
// core::str::from_utf8(r.as_slice())
// .expect("it must be a valid utf8 string")
// });
let path = path.as_ref().map(|x| x.as_ref());
Ok(AccountSigner::new(path).unlock(&root_account))
}
}

0 comments on commit 60e6635

Please sign in to comment.