#[cfg(feature = "std")]
use parity_codec::{Encode, Decode};
#[cfg(feature = "std")]
use regex::Regex;
#[cfg(feature = "std")]
use base58::{FromBase58, ToBase58};
pub const DEV_PHRASE: &str = "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
pub const DEV_ADDRESS: &str = "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV";
#[derive(Debug)]
pub enum Infallible {}
#[cfg(feature = "std")]
pub const JUNCTION_ID_LEN: usize = 32;
pub trait UncheckedFrom<T> {
fn unchecked_from(t: T) -> Self;
}
pub trait UncheckedInto<T> {
fn unchecked_into(self) -> T;
}
impl<S, T: UncheckedFrom<S>> UncheckedInto<T> for S {
fn unchecked_into(self) -> T {
T::unchecked_from(self)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(feature = "std")]
pub enum SecretStringError {
InvalidFormat,
InvalidPhrase,
InvalidPassword,
InvalidSeed,
InvalidSeedLength,
InvalidPath,
}
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Encode, Decode)]
#[cfg(feature = "std")]
pub enum DeriveJunction {
Soft([u8; JUNCTION_ID_LEN]),
Hard([u8; JUNCTION_ID_LEN]),
}
#[cfg(feature = "std")]
impl DeriveJunction {
pub fn soften(self) -> Self { DeriveJunction::Soft(self.unwrap_inner()) }
pub fn harden(self) -> Self { DeriveJunction::Hard(self.unwrap_inner()) }
pub fn soft<T: Encode>(index: T) -> Self {
let mut cc: [u8; JUNCTION_ID_LEN] = Default::default();
index.using_encoded(|data| if data.len() > JUNCTION_ID_LEN {
let hash_result = blake2_rfc::blake2b::blake2b(JUNCTION_ID_LEN, &[], data);
let hash = hash_result.as_bytes();
cc.copy_from_slice(hash);
} else {
cc[0..data.len()].copy_from_slice(data);
});
DeriveJunction::Soft(cc)
}
pub fn hard<T: Encode>(index: T) -> Self {
Self::soft(index).harden()
}
pub fn unwrap_inner(self) -> [u8; JUNCTION_ID_LEN] {
match self {
DeriveJunction::Hard(c) | DeriveJunction::Soft(c) => c,
}
}
pub fn inner(&self) -> &[u8; JUNCTION_ID_LEN] {
match self {
DeriveJunction::Hard(ref c) | DeriveJunction::Soft(ref c) => c,
}
}
pub fn is_soft(&self) -> bool {
match *self {
DeriveJunction::Soft(_) => true,
_ => false,
}
}
pub fn is_hard(&self) -> bool {
match *self {
DeriveJunction::Hard(_) => true,
_ => false,
}
}
}
#[cfg(feature = "std")]
impl<T: AsRef<str>> From<T> for DeriveJunction {
fn from(j: T) -> DeriveJunction {
let j = j.as_ref();
let (code, hard) = if j.starts_with("/") {
(&j[1..], true)
} else {
(j, false)
};
let res = if let Ok(n) = str::parse::<u64>(code) {
DeriveJunction::soft(n)
} else {
DeriveJunction::soft(code)
};
if hard {
res.harden()
} else {
res
}
}
}
#[cfg(feature = "std")]
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub enum PublicError {
BadBase58,
BadLength,
UnknownVersion,
InvalidChecksum,
InvalidFormat,
InvalidPath,
}
#[cfg(feature = "std")]
pub trait Ss58Codec: Sized {
fn from_ss58check(s: &str) -> Result<Self, PublicError>;
fn from_string(s: &str) -> Result<Self, PublicError> { Self::from_ss58check(s) }
fn to_ss58check(&self) -> String;
}
#[cfg(feature = "std")]
pub trait Derive: Sized {
fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, _path: Iter) -> Option<Self> {
None
}
}
#[cfg(feature = "std")]
const PREFIX: &[u8] = b"SS58PRE";
#[cfg(feature = "std")]
fn ss58hash(data: &[u8]) -> blake2_rfc::blake2b::Blake2bResult {
let mut context = blake2_rfc::blake2b::Blake2b::new(64);
context.update(PREFIX);
context.update(data);
context.finalize()
}
#[cfg(feature = "std")]
impl<T: AsMut<[u8]> + AsRef<[u8]> + Default + Derive> Ss58Codec for T {
fn from_ss58check(s: &str) -> Result<Self, PublicError> {
let mut res = T::default();
let len = res.as_mut().len();
let d = s.from_base58().map_err(|_| PublicError::BadBase58)?;
if d.len() != len + 3 {
return Err(PublicError::BadLength);
}
if d[0] != 42 {
return Err(PublicError::UnknownVersion);
}
if d[len+1..len+3] != ss58hash(&d[0..len+1]).as_bytes()[0..2] {
return Err(PublicError::InvalidChecksum);
}
res.as_mut().copy_from_slice(&d[1..len+1]);
Ok(res)
}
fn to_ss58check(&self) -> String {
let mut v = vec![42u8];
v.extend(self.as_ref());
let r = ss58hash(&v);
v.extend(&r.as_bytes()[0..2]);
v.to_base58()
}
fn from_string(s: &str) -> Result<Self, PublicError> {
let re = Regex::new(r"^(?P<ss58>[\w\d]+)?(?P<path>(//?[^/]+)*)$")
.expect("constructed from known-good static value; qed");
let cap = re.captures(s).ok_or(PublicError::InvalidFormat)?;
let re_junction = Regex::new(r"/(/?[^/]+)")
.expect("constructed from known-good static value; qed");
let addr = Self::from_ss58check(
cap.name("ss58")
.map(|r| r.as_str())
.unwrap_or(DEV_ADDRESS)
)?;
if cap["path"].is_empty() {
Ok(addr)
} else {
let path = re_junction.captures_iter(&cap["path"])
.map(|f| DeriveJunction::from(&f[1]));
addr.derive(path)
.ok_or(PublicError::InvalidPath)
}
}
}
#[cfg(feature = "std")]
pub trait Pair: Sized {
type Public;
type Seed;
type Signature;
type DeriveError;
fn generate() -> Self;
fn generate_with_phrase(password: Option<&str>) -> (Self, String);
fn from_phrase(phrase: &str, password: Option<&str>) -> Result<Self, SecretStringError>;
fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, path: Iter) -> Result<Self, Self::DeriveError>;
fn from_seed(seed: Self::Seed) -> Self;
fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError>;
fn from_standard_components<
I: Iterator<Item=DeriveJunction>
>(phrase: &str, password: Option<&str>, path: I) -> Result<Self, SecretStringError>;
fn sign(&self, message: &[u8]) -> Self::Signature;
fn verify<P: AsRef<Self::Public>, M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: P) -> bool;
fn verify_weak<P: AsRef<[u8]>, M: AsRef<[u8]>>(sig: &[u8], message: M, pubkey: P) -> bool;
fn public(&self) -> Self::Public;
fn from_string(s: &str, password_override: Option<&str>) -> Result<Self, SecretStringError> {
let hex_seed = if s.starts_with("0x") {
&s[2..]
} else {
s
};
if let Ok(d) = hex::decode(hex_seed) {
if let Ok(r) = Self::from_seed_slice(&d) {
return Ok(r)
}
}
let re = Regex::new(r"^(?P<phrase>\w+( \w+)*)?(?P<path>(//?[^/]+)*)(///(?P<password>.*))?$")
.expect("constructed from known-good static value; qed");
let cap = re.captures(s).ok_or(SecretStringError::InvalidFormat)?;
let re_junction = Regex::new(r"/(/?[^/]+)")
.expect("constructed from known-good static value; qed");
let path = re_junction.captures_iter(&cap["path"])
.map(|f| DeriveJunction::from(&f[1]));
Self::from_standard_components(
cap.name("phrase").map(|r| r.as_str()).unwrap_or(DEV_PHRASE),
password_override.or_else(|| cap.name("password").map(|m| m.as_str())),
path,
)
}
}
#[cfg(test)]
mod tests {
use crate::DeriveJunction;
use hex_literal::{hex, hex_impl};
use super::*;
#[derive(Eq, PartialEq, Debug)]
enum TestPair {
Generated,
GeneratedWithPhrase,
GeneratedFromPhrase{phrase: String, password: Option<String>},
Standard{phrase: String, password: Option<String>, path: Vec<DeriveJunction>},
Seed(Vec<u8>),
}
impl Pair for TestPair {
type Public = ();
type Seed = ();
type Signature = ();
type DeriveError = ();
fn generate() -> Self { TestPair::Generated }
fn generate_with_phrase(_password: Option<&str>) -> (Self, String) { (TestPair::GeneratedWithPhrase, "".into()) }
fn from_phrase(phrase: &str, password: Option<&str>) -> Result<Self, SecretStringError> {
Ok(TestPair::GeneratedFromPhrase{ phrase: phrase.to_owned(), password: password.map(Into::into) })
}
fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, _path: Iter) -> Result<Self, Self::DeriveError> {
Err(())
}
fn from_seed(_seed: <TestPair as Pair>::Seed) -> Self { TestPair::Seed(vec![]) }
fn sign(&self, _message: &[u8]) -> Self::Signature { () }
fn verify<P: AsRef<Self::Public>, M: AsRef<[u8]>>(_sig: &Self::Signature, _message: M, _pubkey: P) -> bool { true }
fn verify_weak<P: AsRef<[u8]>, M: AsRef<[u8]>>(_sig: &[u8], _message: M, _pubkey: P) -> bool { true }
fn public(&self) -> Self::Public { () }
fn from_standard_components<I: Iterator<Item=DeriveJunction>>(phrase: &str, password: Option<&str>, path: I) -> Result<Self, SecretStringError> {
Ok(TestPair::Standard { phrase: phrase.to_owned(), password: password.map(ToOwned::to_owned), path: path.collect() })
}
fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError> {
Ok(TestPair::Seed(seed.to_owned()))
}
}
#[test]
fn interpret_std_seed_should_work() {
assert_eq!(
TestPair::from_string("0x0123456789abcdef", None),
Ok(TestPair::Seed(hex!["0123456789abcdef"][..].to_owned()))
);
assert_eq!(
TestPair::from_string("0123456789abcdef", None),
Ok(TestPair::Seed(hex!["0123456789abcdef"][..].to_owned()))
);
}
#[test]
fn password_override_should_work() {
assert_eq!(
TestPair::from_string("hello world///password", None),
TestPair::from_string("hello world", Some("password")),
);
assert_eq!(
TestPair::from_string("hello world///password", None),
TestPair::from_string("hello world///other password", Some("password")),
);
}
#[test]
fn interpret_std_secret_string_should_work() {
assert_eq!(
TestPair::from_string("hello world", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![]})
);
assert_eq!(
TestPair::from_string("hello world/1", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::soft(1)]})
);
assert_eq!(
TestPair::from_string("hello world/DOT", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::soft("DOT")]})
);
assert_eq!(
TestPair::from_string("hello world//1", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::hard(1)]})
);
assert_eq!(
TestPair::from_string("hello world//DOT", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::hard("DOT")]})
);
assert_eq!(
TestPair::from_string("hello world//1/DOT", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::hard(1), DeriveJunction::soft("DOT")]})
);
assert_eq!(
TestPair::from_string("hello world//DOT/1", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: None, path: vec![DeriveJunction::hard("DOT"), DeriveJunction::soft(1)]})
);
assert_eq!(
TestPair::from_string("hello world///password", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: Some("password".to_owned()), path: vec![]})
);
assert_eq!(
TestPair::from_string("hello world//1/DOT///password", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: Some("password".to_owned()), path: vec![DeriveJunction::hard(1), DeriveJunction::soft("DOT")]})
);
assert_eq!(
TestPair::from_string("hello world/1//DOT///password", None),
Ok(TestPair::Standard{phrase: "hello world".to_owned(), password: Some("password".to_owned()), path: vec![DeriveJunction::soft(1), DeriveJunction::hard("DOT")]})
);
}
}