Skip to content

Commit

Permalink
merge
Browse files Browse the repository at this point in the history
  • Loading branch information
S0c5 committed Apr 26, 2024
2 parents 4c590fb + d7264e2 commit 45566f1
Show file tree
Hide file tree
Showing 17 changed files with 1,090 additions and 45 deletions.
8 changes: 8 additions & 0 deletions justfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
build-web:
@mkdir -p dist
cargo build --release --target wasm32-unknown-unknown
@cp ./target/wasm32-unknown-unknown/release/pjs.wasm dist/
wasm-bindgen --out-dir dist --target web --no-typescript --remove-name-section dist/pjs.wasm

test:
cargo test
2 changes: 1 addition & 1 deletion libwallet/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ serde = {version = "1.0", default-features = false, features = ["derive"], optio
hmac = {version = "0.12.1", default-features = false, optional = true}
pbkdf2 = {version = "0.11.0", default-features = false, optional = true}
sha2 = {version = "0.10.2", default-features = false, optional = true}
pjs = { git= "https://github.com/S0c5/pjs-rs.git", branch = "feat/get-current-account", optional = true }
pjs = { path = "../pjs-rs", optional = true }
mnemonic = { package = "bip0039", version = "0.10.1", default-features = false, optional = true}

rand_core = {version = "0.6.3", optional = true}
Expand Down
6 changes: 3 additions & 3 deletions libwallet/examples/account_generation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use libwallet::{self, vault};
use libwallet::{self, vault, Account};
use std::env;

type Wallet = libwallet::Wallet<vault::Simple<String>>;
Expand All @@ -16,9 +16,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {

let mut wallet = Wallet::new(vault);
wallet.unlock(None, None).await?;
let account = wallet.default_signer();
let account = wallet.default_account();

println!("Secret phrase: \"{phrase}\"");
// println!("Default Account: 0x{account}");
println!("Default Account: 0x{:?}", account.unwrap());
Ok(())
}
4 changes: 2 additions & 2 deletions libwallet/examples/persisted_in_keyring.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

wallet.unlock(None, pin).await?;

let account = wallet.default_signer();
// println!("Default account: {}", account);
let account = wallet.default_account();
println!("Default account: {}", account.unwrap());

Ok(())
}
7 changes: 4 additions & 3 deletions libwallet/examples/persisted_in_pass.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
use dirs::home_dir;
use libwallet::{self, vault::Pass, Language};
use std::error::Error;
type Wallet = libwallet::Wallet<Pass>;
type PassVault = Pass<String>;
type Wallet = libwallet::Wallet<PassVault>;

#[async_std::main]
async fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -15,8 +16,8 @@ async fn main() -> Result<(), Box<dyn Error>> {

wallet.unlock(None, account).await?;

let account = wallet.default_signer();
// println!("Default account: {}", account);
let account = wallet.default_account();
println!("Default account: {}", account.unwrap());

Ok(())
}
9 changes: 4 additions & 5 deletions libwallet/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use core::fmt::{Debug, Display};

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


pub trait Account: Signer {
pub trait Account: Signer + Display {
fn public(&self) -> impl Public;
}
14 changes: 7 additions & 7 deletions libwallet/src/key_pair.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ impl<const N: usize> Signature for Bytes<N> {}
/// Something that can sign messages
pub trait Signer {
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;
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;
}
/// Wrappers to represent any supported key pair.
pub mod any {
Expand Down Expand Up @@ -94,14 +94,14 @@ pub mod any {
impl super::Signer for Pair {
type Signature = AnySignature;

async fn sign_msg<M: AsRef<[u8]>>(&self, msg: M) -> Result<Self::Signature, ()> {
async fn sign_msg(&self, msg: impl AsRef<[u8]>) -> Result<Self::Signature, ()> {
match self {
#[cfg(feature = "sr25519")]
Pair::Sr25519(p) => Ok(p.sign_msg(msg).await?.into()),
}
}

async fn verify<M: AsRef<[u8]>>(&self, msg: M, sig: &[u8]) -> bool {
async fn verify(&self, msg: impl AsRef<[u8]>, sig: impl AsRef<[u8]>) -> bool {
match self {
#[cfg(feature = "sr25519")]
Pair::Sr25519(p) => super::Signer::verify(p, msg, sig).await,
Expand Down Expand Up @@ -200,13 +200,13 @@ pub mod sr25519 {
impl Signer for Pair {
type Signature = Signature;

async fn sign_msg<M: AsRef<[u8]>>(&self, msg: M) -> Result<Self::Signature, ()> {
async fn sign_msg(&self, msg: impl AsRef<[u8]>) -> Result<Self::Signature, ()> {
let context = signing_context(SIGNING_CTX);
Ok(self.sign(context.bytes(msg.as_ref())).to_bytes())
}

async fn verify<M: AsRef<[u8]>>(&self, msg: M, sig: &[u8]) -> bool {
let sig = match schnorrkel::Signature::from_bytes(sig) {
async fn verify(&self, msg: impl AsRef<[u8]>, sig: impl AsRef<[u8]>) -> bool {
let sig = match schnorrkel::Signature::from_bytes(sig.as_ref()) {
Ok(s) => s,
Err(_) => return false,
};
Expand Down
10 changes: 5 additions & 5 deletions libwallet/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub mod util;
#[cfg(feature = "substrate")]
mod substrate_ext;

use account::Account;
pub use account::Account;
use arrayvec::ArrayVec;
use core::{cell::RefCell, convert::TryInto, fmt};
use key_pair::any::AnySignature;
Expand Down Expand Up @@ -66,7 +66,7 @@ where
}

/// Get the account currently set as default
pub fn default_signer(&self) -> Option<&V::Account> {
pub fn default_account(&self) -> Option<&V::Account> {
self.default_account.map(|x| &self.accounts[x as usize])
}

Expand Down Expand Up @@ -132,13 +132,13 @@ where
/// let msg = &[0x12, 0x34, 0x56];
/// let signature = wallet.sign(msg).await.expect("it must sign");
///
/// assert!(wallet.default_signer().expect("it must have a default signer").verify(msg, signature.as_ref()).await);
/// assert!(wallet.default_account().expect("it must have a default signer").verify(msg, signature.as_ref()).await);
/// # Ok(()) }
/// ```
pub async fn sign(&self, message: &[u8]) -> Result<impl Signature, ()> {
assert!(!self.is_locked());

let Some(signer) = self.default_signer() else {
let Some(signer) = self.default_account() else {
return Err(());
};

Expand Down Expand Up @@ -194,7 +194,7 @@ where
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"));
.unwrap_or_else(|| self.default_account().expect("Signer not set"));

let message = signer.sign_msg(&msg).await?;
signatures.push(message);
Expand Down
15 changes: 8 additions & 7 deletions libwallet/src/vault.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,22 @@
#[cfg(feature = "vault_os")]
mod os;

#[cfg(feature = "vault_os")]
pub use os::*;
#[cfg(feature = "vault_pjs")]
pub mod pjs;

#[cfg(feature = "vault_pjs")]
pub use pjs::*;

#[cfg(feature = "vault_pass")]
mod pass;
mod simple;

#[cfg(feature = "vault_pass")]
pub use pass::*;

mod simple;
pub use simple::*;


#[cfg(feature = "vault_pjs")]
pub use pjs::*;


use crate::account::Account;
Expand Down Expand Up @@ -140,7 +141,7 @@ mod utils {
impl crate::Signer for AccountSigner {
type Signature = AnySignature;

async fn sign_msg<M: AsRef<[u8]>>(&self, msg: M) -> Result<Self::Signature, ()> {
async fn sign_msg(&self, msg: impl AsRef<[u8]>) -> Result<Self::Signature, ()> {
Ok(self
.pair
.as_ref()
Expand All @@ -149,7 +150,7 @@ mod utils {
.await?)
}

async fn verify<M: AsRef<[u8]>>(&self, msg: M, sig: &[u8]) -> bool {
async fn verify(&self, msg: impl AsRef<[u8]>, sig: impl AsRef<[u8]>) -> bool {
self.pair
.as_ref()
.expect("account unlocked")
Expand Down
17 changes: 9 additions & 8 deletions libwallet/src/vault/pass.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use core::marker::PhantomData;

use arrayvec::ArrayVec;
use mnemonic::Language;
use prs_lib::{
Expand All @@ -14,15 +16,16 @@ use crate::{
};

/// A vault that stores secrets in a `pass` compatible repository
pub struct Pass {
pub struct Pass<Id> {
store: Store,
root: Option<RootAccount>,
auto_generate: Option<Language>,
_phantom_data: PhantomData<Id>,
}

const DEFAULT_DIR: &str = "libwallet_accounts/";

impl Pass {
impl<Id> Pass<Id> {
/// Create a new `Pass` vault in the given location.
/// The optional `lang` instructs the vault to generarte a backup phrase
/// in the given language in case one does not exist.
Expand All @@ -33,6 +36,7 @@ impl Pass {
store,
root: None,
auto_generate: lang.into(),
_phantom_data: Default::default(),
}
}

Expand Down Expand Up @@ -135,8 +139,8 @@ impl From<String> for PassCreds {
}
}

impl Vault for Pass {
type Id = Option<ArrayVec<u8, 20>>;
impl<Id: AsRef<str>> Vault for Pass<Id> {
type Id = Option<Id>;
type Credentials = PassCreds;
type Account = AccountSigner;
type Error = Error;
Expand All @@ -155,10 +159,7 @@ impl Vault for Pass {
.and_then(|l| self.generate(&credentials, l))
})
.map(|r| {
let acc = AccountSigner::new(path.as_ref().map(|x| {
core::str::from_utf8(x.as_slice()).expect("it must be a valid utf8 string")
}))
.unlock(&r);
let acc = AccountSigner::new(path.as_ref().map(|x| x.as_ref())).unlock(&r);
self.root = Some(r);
acc
})
Expand Down
4 changes: 0 additions & 4 deletions libwallet/src/vault/simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,6 @@ impl<S: AsRef<str>> Vault for Simple<S> {
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(|x| x.as_ref());
Ok(AccountSigner::new(path).unlock(&root_account))
}
Expand Down
17 changes: 17 additions & 0 deletions pjs-rs/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
[package]
name = "pjs"
version = "0.1.0"
edition = "2021"

[dependencies]
wasm-bindgen = { version = "0.2.92", default-features = false }
wasm-bindgen-futures = "0.4.42"

[dependencies.web-sys]
version = "0.3.69"
features = [
"Window",
]

[lib]
crate-type = ["cdylib"]
Loading

0 comments on commit 45566f1

Please sign in to comment.