Skip to content

Commit

Permalink
feat: update the libwallet interface
Browse files Browse the repository at this point in the history
  • Loading branch information
S0c5 committed Apr 25, 2024
1 parent ad5cb5c commit ccb94c8
Show file tree
Hide file tree
Showing 5 changed files with 44 additions and 33 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))
}
}
7 changes: 3 additions & 4 deletions sube/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ log = "0.4.17"
async-trait = "0.1.53"
blake2 = { version = "0.10.5", default-features = false }
codec = { version = "3.1.2", package = "parity-scale-codec", default-features = false }
frame-metadata = { version = "15.0.0", git = "https://github.com/paritytech/frame-metadata.git", default-features = false, features = ["serde_full", "decode"] }
frame-metadata = { version = "16.0.0", git = "https://github.com/paritytech/frame-metadata.git", default-features = false, features = ["serde_full", "decode"] }
hex = { version = "0.4.3", default-features = false, features = ["alloc"] }
twox-hash = { version = "1.6.2", default-features = false }
serde = { version = "1.0.137", default-features = false }
Expand Down Expand Up @@ -54,9 +54,8 @@ http-web = ["jsonrpc", "surf/wasm-client"]
json = ["v14", "scales/json"]
std = []
builder = []
v12 = ["frame-metadata/v12"]
v13 = ["frame-metadata/v13"]
v14 = ["frame-metadata/v14", "scale-info"]

v14 = ["scale-info"]
ws = ["async-std", "async-tungstenite", "async-mutex", "futures-util", "futures-channel", "jsonrpc"]
wss = ["ws", "async-tls", "async-tungstenite/async-tls"]

Expand Down

0 comments on commit ccb94c8

Please sign in to comment.