Make subkey support Sr25519 crypto (#1933)

* Make subkey support Sr25519 crypto.

* Rebuild runtime.

* Build and rejig locks.

* Fix grumbles

* Derivations

* Introduce tests
This commit is contained in:
Gav Wood
2019-03-07 17:10:17 +01:00
committed by GitHub
parent 9ad06d57fc
commit 9f3b4468db
13 changed files with 2172 additions and 1118 deletions
+61 -3
View File
@@ -914,6 +914,15 @@ dependencies = [
"crunchy 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "hashbrown"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "heapsize"
version = "0.4.2"
@@ -2073,6 +2082,9 @@ dependencies = [
name = "once_cell"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"parking_lot 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "opaque-debug"
@@ -2295,6 +2307,16 @@ dependencies = [
"syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "pbkdf2"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"byteorder 1.3.1 (registry+https://github.com/rust-lang/crates.io-index)",
"crypto-mac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rayon 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "peeking_take_while"
version = "0.1.2"
@@ -2748,7 +2770,7 @@ dependencies = [
[[package]]
name = "schnorrkel"
version = "0.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
source = "git+https://github.com/w3f/schnorrkel#0876f3f2194426150efea99304a8d23a336744bc"
dependencies = [
"clear_on_drop 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)",
"curve25519-dalek 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -2757,6 +2779,7 @@ dependencies = [
"merlin 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rand_chacha 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)",
"sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"sha3 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)",
"subtle 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
@@ -3559,7 +3582,11 @@ version = "0.1.0"
dependencies = [
"clap 2.32.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"schnorrkel 0.0.0 (git+https://github.com/w3f/schnorrkel)",
"substrate-bip39 0.2.0 (git+https://github.com/paritytech/substrate-bip39)",
"substrate-primitives 0.1.0",
"tiny-bip39 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
@@ -3589,6 +3616,17 @@ dependencies = [
"substrate-transaction-pool 0.1.0",
]
[[package]]
name = "substrate-bip39"
version = "0.2.0"
source = "git+https://github.com/paritytech/substrate-bip39#a28806512c977992af8d6740d45352f5a1c832a0"
dependencies = [
"hmac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"pbkdf2 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"schnorrkel 0.0.0 (git+https://github.com/w3f/schnorrkel)",
"sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "substrate-cli"
version = "0.3.0"
@@ -3952,12 +3990,14 @@ dependencies = [
"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"ring 0.14.6 (registry+https://github.com/rust-lang/crates.io-index)",
"rustc-hex 2.0.1 (registry+https://github.com/rust-lang/crates.io-index)",
"schnorrkel 0.0.0 (registry+https://github.com/rust-lang/crates.io-index)",
"schnorrkel 0.0.0 (git+https://github.com/w3f/schnorrkel)",
"serde 1.0.87 (registry+https://github.com/rust-lang/crates.io-index)",
"serde_derive 1.0.87 (registry+https://github.com/rust-lang/crates.io-index)",
"sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
"sr-std 0.1.0",
"substrate-bip39 0.2.0 (git+https://github.com/paritytech/substrate-bip39)",
"substrate-serializer 0.1.0",
"tiny-bip39 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)",
"twox-hash 1.1.2 (registry+https://github.com/rust-lang/crates.io-index)",
"untrusted 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)",
"wasmi 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)",
@@ -4318,6 +4358,20 @@ dependencies = [
"winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "tiny-bip39"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
dependencies = [
"failure 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)",
"hashbrown 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
"hmac 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)",
"once_cell 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)",
"pbkdf2 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)",
"rand 0.6.5 (registry+https://github.com/rust-lang/crates.io-index)",
"sha2 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)",
]
[[package]]
name = "tiny-keccak"
version = "1.4.2"
@@ -5040,6 +5094,7 @@ dependencies = [
"checksum h2 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "ddb2b25a33e231484694267af28fec74ac63b5ccf51ee2065a5e313b834d836e"
"checksum hash-db 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1b03501f6e1a2a97f1618879aba3156f14ca2847faa530c4e28859638bd11483"
"checksum hash256-std-hasher 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "f5c13dbac3cc50684760f54af18545c9e80fb75e93a3e586d71ebdc13138f6a4"
"checksum hashbrown 0.1.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3bae29b6653b3412c2e71e9d486db9f9df5d701941d86683005efb9f2d28e3da"
"checksum heapsize 0.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "1679e6ea370dee694f91f1dc469bf94cf8f52051d147aec3e1f9497c6fc22461"
"checksum heck 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)" = "20564e78d53d2bb135c343b3f47714a56af2061f1c928fdb541dc7b9fdd94205"
"checksum hex 0.3.2 (registry+https://github.com/rust-lang/crates.io-index)" = "805026a5d0141ffc30abb3be3173848ad46a1b1664fe632428479619a3644d77"
@@ -5153,6 +5208,7 @@ dependencies = [
"checksum parking_lot_core 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94c8c7923936b28d546dfd14d4472eaf34c99b14e1c973a32b3e6d4eb04298c9"
"checksum paste 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "f50392d1265092fbee9273414cc40eb6d47d307bd66222c477bb8450c8504f9d"
"checksum paste-impl 0.1.4 (registry+https://github.com/rust-lang/crates.io-index)" = "a3cd512fe3a55e8933b2dcad913e365639db86d512e4004c3084b86864d9467a"
"checksum pbkdf2 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "006c038a43a45995a9670da19e67600114740e8511d4333bf97a56e66a7542d9"
"checksum peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099"
"checksum percent-encoding 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "31010dd2e1ac33d5b46a5b413495239882813e0369f8ed8a5e266f173602f831"
"checksum pkg-config 0.3.14 (registry+https://github.com/rust-lang/crates.io-index)" = "676e8eb2b1b4c9043511a9b7bea0915320d7e502b0a079fb03f9635a5252b18c"
@@ -5207,7 +5263,7 @@ dependencies = [
"checksum safemem 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8dca453248a96cb0749e36ccdfe2b0b4e54a61bfef89fb97ec621eb8e0a93dd9"
"checksum same-file 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "8f20c4be53a8a1ff4c1f1b2bd14570d2f634628709752f0702ecdd2b3f9a5267"
"checksum schannel 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "0e1a231dc10abf6749cfa5d7767f25888d484201accbd919b66ab5413c502d56"
"checksum schnorrkel 0.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fe554f318830b48e5da8ab1ccb1ffd02b79228364dac7766b7cd1ec461ca5116"
"checksum schnorrkel 0.0.0 (git+https://github.com/w3f/schnorrkel)" = "<none>"
"checksum scopeguard 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "94258f53601af11e6a49f722422f6e3425c52b06245a5cf9bc09908b174f5e27"
"checksum secp256k1 0.12.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfaccd3a23619349e0878d9a241f34b1982343cdf67367058cd7d078d326b63e"
"checksum security-framework 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "bfab8dda0e7a327c696d893df9ffa19cadc4bd195797997f5223cf5831beaf05"
@@ -5242,6 +5298,7 @@ dependencies = [
"checksum strsim 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb4f380125926a99e52bc279241539c018323fab05ad6368b56f93d9369ff550"
"checksum structopt 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "670ad348dc73012fcf78c71f06f9d942232cdd4c859d4b6975e27836c3efc0c3"
"checksum structopt-derive 0.2.14 (registry+https://github.com/rust-lang/crates.io-index)" = "ef98172b1a00b0bec738508d3726540edcbd186d50dfd326f2b1febbb3559f04"
"checksum substrate-bip39 0.2.0 (git+https://github.com/paritytech/substrate-bip39)" = "<none>"
"checksum subtle 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2d67a5a62ba6e01cb2192ff309324cb4875d0c451d55fe2319433abe7a05a8ee"
"checksum subtle 2.0.0 (registry+https://github.com/rust-lang/crates.io-index)" = "702662512f3ddeb74a64ce2fbbf3707ee1b6bb663d28bb054e0779bbc720d926"
"checksum syn 0.15.26 (registry+https://github.com/rust-lang/crates.io-index)" = "f92e629aa1d9c827b2bb8297046c1ccffc57c99b947a680d3ccff1f136a3bee9"
@@ -5256,6 +5313,7 @@ dependencies = [
"checksum textwrap 0.10.0 (registry+https://github.com/rust-lang/crates.io-index)" = "307686869c93e71f94da64286f9a9524c0f308a9e1c87a583de8e9c9039ad3f6"
"checksum thread_local 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "c6b53e329000edc2b34dbe8545fd20e55a333362d0a321909685a19bd28c3f1b"
"checksum time 0.1.42 (registry+https://github.com/rust-lang/crates.io-index)" = "db8dcfca086c1143c9270ac42a2bbd8a7ee477b78ac8e45b19abfb0cbede4b6f"
"checksum tiny-bip39 0.6.0 (registry+https://github.com/rust-lang/crates.io-index)" = "a1415431cb2398d84da64173f8473c792808314427d4a6f2f3ea85ae67239fe3"
"checksum tiny-keccak 1.4.2 (registry+https://github.com/rust-lang/crates.io-index)" = "e9175261fbdb60781fcd388a4d6cc7e14764a2b629a7ad94abb439aed223a44f"
"checksum tinytemplate 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7655088894274afb52b807bd3c87072daa1fedd155068b8705cabfd628956115"
"checksum tk-listen 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "5462b0f968c0457efe38fcd2df7e487096b992419e4f5337b06775a614bbda4b"
+5 -1
View File
@@ -22,9 +22,11 @@ untrusted = { version = "0.6", optional = true }
hex-literal = { version = "0.1", optional = true }
base58 = { version = "0.1", optional = true }
blake2-rfc = { version = "0.2.18", optional = true }
schnorrkel = { version = "0.0", optional = true }
schnorrkel = { git = "https://github.com/w3f/schnorrkel", optional = true }
rand = { version = "0.6", optional = true }
sha2 = { version = "0.8", optional = true }
substrate-bip39 = { git = "https://github.com/paritytech/substrate-bip39", optional = true }
tiny-bip39 = { version = "0.6.0", optional = true }
[dev-dependencies]
substrate-serializer = { path = "../serializer" }
@@ -54,6 +56,8 @@ std = [
"untrusted",
"hex-literal",
"base58",
"substrate-bip39",
"tiny-bip39",
"serde_derive",
"byteorder/std",
"rand",
+211 -7
View File
@@ -21,10 +21,14 @@
use base58::{FromBase58, ToBase58};
use blake2_rfc;
use rand::rngs::OsRng;
use schnorrkel::{signing_context, Keypair, MiniSecretKey, PublicKey};
use sha2::Sha512;
use schnorrkel::{signing_context, Keypair, SecretKey, MiniSecretKey, PublicKey,
derive::{Derivation, ChainCode, CHAIN_CODE_LENGTH}
};
use substrate_bip39::mini_secret_from_entropy;
//use sha2::Sha512;
use parity_codec::{Encode, Decode};
use crate::hash::H512;
use bip39::{Mnemonic, Language};
#[cfg(feature = "std")]
use serde::{de, Deserialize, Deserializer, Serializer};
@@ -32,6 +36,8 @@ use serde::{de, Deserialize, Deserializer, Serializer};
// signing context
const SIGNING_CTX: &'static [u8] = b"substrate transaction";
/// An Schnorrkel/Ristretto x25519 ("sr25519") signature.
///
/// Instead of importing it for the local module, alias it to be available as a public type
pub type Signature = H512;
@@ -45,11 +51,11 @@ pub struct LocalizedSignature {
pub signature: Signature,
}
/// A public key.
/// An Schnorrkel/Ristretto x25519 ("sr25519") public key.
#[derive(PartialEq, Eq, Clone, Encode, Decode)]
pub struct Public(pub [u8; 32]);
/// A schnorrkel key pair.
/// An Schnorrkel/Ristretto x25519 ("sr25519") key pair.
pub struct Pair(Keypair);
impl ::std::hash::Hash for Public {
@@ -127,6 +133,20 @@ impl Public {
v.extend(&r.as_bytes()[0..2]);
v.to_base58()
}
/// Derive a child key from a series of given junctions.
///
/// `None` if there are any hard junctions in there.
pub fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, mut path: Iter) -> Option<Public> {
let mut acc = PublicKey::from_bytes(self.as_ref()).ok()?;
for j in path {
match j {
DeriveJunction::Soft(cc) => acc = acc.derived_key_simple(ChainCode(cc), &[]).0,
DeriveJunction::Hard(cc) => return None,
}
}
Some(Self(acc.to_bytes()))
}
}
impl AsRef<[u8; 32]> for Public {
@@ -159,6 +179,36 @@ impl AsRef<Pair> for Pair {
}
}
impl From<MiniSecretKey> for Pair {
fn from(sec: MiniSecretKey) -> Pair {
Pair(sec.expand_to_keypair())
}
}
impl From<SecretKey> for Pair {
fn from(sec: SecretKey) -> Pair {
Pair(Keypair::from(sec))
}
}
impl From<schnorrkel::Keypair> for Pair {
fn from(p: schnorrkel::Keypair) -> Pair {
Pair(p)
}
}
impl From<Pair> for schnorrkel::Keypair {
fn from(p: Pair) -> schnorrkel::Keypair {
p.0
}
}
impl AsRef<schnorrkel::Keypair> for Pair {
fn as_ref(&self) -> &schnorrkel::Keypair {
&self.0
}
}
impl ::std::fmt::Display for Public {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.to_ss58check())
@@ -172,12 +222,95 @@ impl ::std::fmt::Debug for Public {
}
}
/// A since derivation junction description. It is the single parameter used when creating
/// a new secret key from an existing secret key and, in the case of `SoftRaw` and `SoftIndex`
/// a new public key from an existing public key.
#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Encode, Decode)]
pub enum DeriveJunction {
/// Soft (vanilla) derivation. Public keys have a correspondent derivation.
Soft([u8; CHAIN_CODE_LENGTH]),
/// Hard ("hardened") derivation. Public keys do not have a correspondent derivation.
Hard([u8; CHAIN_CODE_LENGTH]),
}
impl DeriveJunction {
/// Consume self to return a soft derive junction with the same chain code.
pub fn soften(self) -> Self { DeriveJunction::Soft(self.unwrap_inner()) }
/// Consume self to return a hard derive junction with the same chain code.
pub fn harden(self) -> Self { DeriveJunction::Hard(self.unwrap_inner()) }
/// Create a new soft (vanilla) DeriveJunction from a given, encodable, value.
///
/// If you need a hard junction, use `hard()`.
pub fn soft<T: Encode>(index: T) -> Self {
let mut cc: [u8; CHAIN_CODE_LENGTH] = Default::default();
index.using_encoded(|data| if data.len() > CHAIN_CODE_LENGTH {
let hash_result = blake2_rfc::blake2b::blake2b(CHAIN_CODE_LENGTH, &[], data);
let hash = hash_result.as_bytes();
cc.copy_from_slice(hash);
} else {
cc[0..data.len()].copy_from_slice(data);
});
DeriveJunction::Soft(cc)
}
/// Create a new hard (hardened) DeriveJunction from a given, encodable, value.
///
/// If you need a soft junction, use `soft()`.
pub fn hard<T: Encode>(index: T) -> Self {
Self::soft(index).harden()
}
/// Consume self to return the chain code.
pub fn unwrap_inner(self) -> [u8; CHAIN_CODE_LENGTH] {
match self {
DeriveJunction::Hard(c) | DeriveJunction::Soft(c) => c,
}
}
/// Consume self to return the chain code.
pub fn unwrap_chain_code(self) -> ChainCode {
ChainCode(self.unwrap_inner())
}
/// Return a reference to the chain code.
pub fn chain_code(&self) -> ChainCode {
self.clone().unwrap_chain_code()
}
/// Return `true` if the junction is soft.
pub fn is_soft(&self) -> bool {
match *self {
DeriveJunction::Soft(_) => true,
_ => false,
}
}
/// Return `true` if the junction is hard.
pub fn is_hard(&self) -> bool {
match *self {
DeriveJunction::Hard(_) => true,
_ => false,
}
}
}
/// Derive a single hard junction.
fn derive_hard_junction(secret: &SecretKey, cc: &[u8; CHAIN_CODE_LENGTH]) -> SecretKey {
("SchnorrRistrettoHDKD", &secret.to_bytes()[..], cc).using_encoded(|data|
MiniSecretKey::from_bytes(blake2_rfc::blake2b::blake2b(32, &[], data).as_bytes())
.expect("all 32-byte crypto-hash results are valid MiniSecretKeys; qed")
.expand()
)
}
impl Pair {
/// Generate new secure (random) key pair.
pub fn generate() -> Pair {
let mut csprng: OsRng = OsRng::new().expect("os random generator works; qed");
let keypair: Keypair = Keypair::generate(&mut csprng);
Pair(keypair)
let key_pair: Keypair = Keypair::generate(&mut csprng);
Pair(key_pair)
}
/// Make a new key pair from a seed phrase.
@@ -186,10 +319,37 @@ impl Pair {
pub fn from_seed(seed: &[u8; 32]) -> Pair {
let mini_key: MiniSecretKey = MiniSecretKey::from_bytes(seed)
.expect("32 bytes can always build a key; qed");
let kp = mini_key.expand_to_keypair::<Sha512>();
let kp = mini_key.expand_to_keypair();
Pair(kp)
}
/// Make a new key pair from a seed phrase.
/// This is generated using schnorrkel's Mini-Secret-Keys.
/// A MiniSecretKey is literally what Ed25519 calls a SecretKey, which is just 32 random bytes.
pub fn from_entropy(entropy: &[u8], password: Option<&str>) -> Pair {
let mini_key: MiniSecretKey = mini_secret_from_entropy(entropy, password.unwrap_or(""))
.expect("32 bytes can always build a key; qed");
let kp = mini_key.expand_to_keypair();
Pair(kp)
}
/// Returns the KeyPair from the English BIP39 seed `phrase`, or `None` if it's invalid.
pub fn from_phrase(phrase: &str, password: Option<&str>) -> Option<Pair> {
Mnemonic::from_phrase(phrase, Language::English)
.ok()
.map(|m| Self::from_entropy(m.entropy(), password))
}
/// Derive a child key from a series of given junctions.
pub fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, mut path: Iter) -> Pair {
let init = self.0.secret.clone();
let result = path.fold(init, |acc, j| match j {
DeriveJunction::Soft(cc) => acc.derived_key_simple(ChainCode(cc), &[]).0,
DeriveJunction::Hard(cc) => derive_hard_junction(&acc, &cc),
});
Self(result.into())
}
/// Sign a message.
pub fn sign(&self, message: &[u8]) -> Signature {
let context = signing_context(SIGNING_CTX);
@@ -274,6 +434,50 @@ mod test {
use super::*;
use hex_literal::{hex, hex_impl};
#[test]
fn derive_soft_should_work() {
let pair: Pair = Pair::from_seed(&hex!(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
));
let derive_1 = pair.derive(Some(DeriveJunction::soft(1)).into_iter());
let derive_1b = pair.derive(Some(DeriveJunction::soft(1)).into_iter());
let derive_2 = pair.derive(Some(DeriveJunction::soft(2)).into_iter());
assert_eq!(derive_1.public(), derive_1b.public());
assert_ne!(derive_1.public(), derive_2.public());
}
#[test]
fn derive_hard_should_work() {
let pair: Pair = Pair::from_seed(&hex!(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
));
let derive_1 = pair.derive(Some(DeriveJunction::hard(1)).into_iter());
let derive_1b = pair.derive(Some(DeriveJunction::hard(1)).into_iter());
let derive_2 = pair.derive(Some(DeriveJunction::hard(2)).into_iter());
assert_eq!(derive_1.public(), derive_1b.public());
assert_ne!(derive_1.public(), derive_2.public());
}
#[test]
fn derive_soft_public_should_work() {
let pair: Pair = Pair::from_seed(&hex!(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
));
let path = Some(DeriveJunction::soft(1));
let pair_1 = pair.derive(path.clone().into_iter());
let public_1 = pair.public().derive(path.into_iter()).unwrap();
assert_eq!(pair_1.public(), public_1);
}
#[test]
fn derive_hard_public_should_fail() {
let pair: Pair = Pair::from_seed(&hex!(
"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
));
let path = Some(DeriveJunction::hard(1));
assert!(pair.public().derive(path.into_iter()).is_none());
}
#[test]
fn sr_test_vector_should_work() {
let pair: Pair = Pair::from_seed(&hex!(
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -61,7 +61,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion {
impl_name: create_runtime_str!("substrate-node"),
authoring_version: 10,
spec_version: 34,
impl_version: 34,
impl_version: 35,
apis: RUNTIME_API_VERSIONS,
};
+620 -399
View File
File diff suppressed because it is too large Load Diff
+4
View File
@@ -8,6 +8,10 @@ edition = "2018"
substrate-primitives = { version = "*", path = "../core/primitives" }
rand = "0.6"
clap = { version = "~2.32", features = ["yaml"] }
tiny-bip39 = "0.6.0"
rustc-hex = "2.0"
substrate-bip39 = { git = "https://github.com/paritytech/substrate-bip39" }
schnorrkel = { git = "https://github.com/w3f/schnorrkel" }
[features]
bench = []
+29 -1
View File
@@ -1,6 +1,28 @@
name: subkey
author: "Parity Team <admin@parity.io>"
about: A substrate key utility
args:
- ed25519-legacy:
short: o
long: legacy
help: Use legacy, outdated Ed25519 cryptography
takes_value: false
- ed25519:
short: e
long: ed25519
help: Use Ed25519/BIP39 cryptography
takes_value: false
- sr25519:
short: s
long: sr25519
help: Use Schnorr/Ristretto x25519/BIP39 cryptography
takes_value: false
- password:
short: p
long: password
takes_value: true
required: false
help: The password for the key
subcommands:
- generate:
about: Generate a random account
@@ -14,7 +36,7 @@ subcommands:
it will be right-padded with 0x20 bytes (ASCII space). If the provided seed is longer than
32 bytes then seed will be truncated.
- vanity:
about: Generate vanity address
about: Generate a seed that provides a vanity address
args:
- pattern:
index: 1
@@ -25,3 +47,9 @@ subcommands:
help: Number of keys to generate
takes_value: true
default_value: "1"
- query:
about: Query an account by its seed
args:
- seed:
index: 1
help: The 0x prefixed seed
+161 -41
View File
@@ -18,58 +18,178 @@
#[cfg(feature = "bench")]
extern crate test;
extern crate substrate_bip39;
extern crate rustc_hex;
use clap::load_yaml;
use rand::{RngCore, rngs::OsRng};
use substrate_primitives::{ed25519::Pair, hexdisplay::HexDisplay};
use substrate_bip39::{mini_secret_from_entropy};
use bip39::{Mnemonic, Language, MnemonicType};
use substrate_primitives::{ed25519, sr25519, hexdisplay::HexDisplay};
use schnorrkel::keys::MiniSecretKey;
use rustc_hex::FromHex;
mod vanity;
fn print_account(seed: &[u8; 32]) {
let pair = Pair::from_seed(seed);
println!("Seed 0x{} is account:\n Public key (hex): 0x{}\n Address (SS58): {}",
HexDisplay::from(seed),
HexDisplay::from(&pair.public().0),
pair.public().to_ss58check()
);
trait Crypto {
type Seed: AsRef<[u8]> + AsMut<[u8]> + Sized + Default;
type Pair;
fn generate_phrase() -> String {
Mnemonic::new(MnemonicType::Words12, Language::English).phrase().to_owned()
}
fn generate_seed() -> Self::Seed;
fn seed_from_phrase(phrase: &str, password: Option<&str>) -> Self::Seed;
fn pair_from_seed(seed: &Self::Seed) -> Self::Pair;
fn pair_from_phrase(phrase: &str, password: Option<&str>) -> Self::Pair {
Self::pair_from_seed(&Self::seed_from_phrase(phrase, password))
}
fn ss58_from_pair(pair: &Self::Pair) -> String;
fn public_from_pair(pair: &Self::Pair) -> Vec<u8>;
fn print_from_seed(seed: &Self::Seed) {
let pair = Self::pair_from_seed(seed);
println!("Seed 0x{} is account:\n Public key (hex): 0x{}\n Address (SS58): {}",
HexDisplay::from(&seed.as_ref()),
HexDisplay::from(&Self::public_from_pair(&pair)),
Self::ss58_from_pair(&pair)
);
}
fn print_from_phrase(phrase: &str, password: Option<&str>) {
let seed = Self::seed_from_phrase(phrase, password);
let pair = Self::pair_from_seed(&seed);
println!("Phrase `{}` is account:\n Seed: 0x{}\n Public key (hex): 0x{}\n Address (SS58): {}",
phrase,
HexDisplay::from(&seed.as_ref()),
HexDisplay::from(&Self::public_from_pair(&pair)),
Self::ss58_from_pair(&pair)
);
}
}
struct OriginalEd25519;
impl Crypto for OriginalEd25519 {
type Seed = [u8; 32];
type Pair = ed25519::Pair;
fn generate_seed() -> Self::Seed {
let mut seed = [0u8; 32];
OsRng::new().unwrap().fill_bytes(&mut seed[..]);
seed
}
fn seed_from_phrase(phrase: &str, password: Option<&str>) -> Self::Seed {
if password.is_some() {
panic!("Ed25519 original doesn't support passwords")
}
let mut raw_seed = phrase.as_bytes();
if raw_seed.len() > 32 {
raw_seed = &raw_seed[..32];
println!("seed is too long and will be truncated to: {}", HexDisplay::from(&raw_seed));
}
// Copy the raw_seed into a buffer that already contains ' ' 0x20.
// This will effectively get us padding for seeds shorter than 32.
let mut seed = [' ' as u8; 32];
let len = raw_seed.len().min(32);
seed[..len].copy_from_slice(&raw_seed[..len]);
seed
}
fn pair_from_seed(seed: &Self::Seed) -> Self::Pair { ed25519::Pair::from_seed(seed) }
fn ss58_from_pair(pair: &Self::Pair) -> String { pair.public().to_ss58check() }
fn public_from_pair(pair: &Self::Pair) -> Vec<u8> { (&pair.public().0[..]).to_owned() }
}
struct Sr25519;
impl Crypto for Sr25519 {
type Seed = [u8; 32];
type Pair = sr25519::Pair;
fn generate_seed() -> Self::Seed {
let mut seed = [0u8; 32];
OsRng::new().unwrap().fill_bytes(&mut seed[..]);
seed
}
fn seed_from_phrase(phrase: &str, password: Option<&str>) -> Self::Seed {
mini_secret_from_entropy(
Mnemonic::from_phrase(phrase, Language::English)
.unwrap_or_else(|_|
panic!("Phrase is not a valid BIP-39 phrase: \n {}", phrase)
)
.entropy(),
password.unwrap_or("")
)
.expect("32 bytes can always build a key; qed")
.to_bytes()
}
fn pair_from_phrase(phrase: &str, password: Option<&str>) -> Self::Pair {
sr25519::Pair::from_phrase(phrase, password)
.unwrap_or_else(||
panic!("Phrase is not a valid BIP-39 phrase: \n {}", phrase)
)
}
fn pair_from_seed(seed: &Self::Seed) -> Self::Pair {
MiniSecretKey::from_bytes(seed)
.expect("32 bytes can always build a key; qed")
.into()
}
fn ss58_from_pair(pair: &Self::Pair) -> String { pair.public().to_ss58check() }
fn public_from_pair(pair: &Self::Pair) -> Vec<u8> { (&pair.public().0[..]).to_owned() }
}
fn execute<C: Crypto<Seed=[u8; 32]>>(matches: clap::ArgMatches) {
let password = matches.value_of("password");
match matches.subcommand() {
("generate", Some(_matches)) => {
// create a new randomly generated mnemonic phrase
let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::English);
C::print_from_phrase(mnemonic.phrase(), password);
},
("vanity", Some(matches)) => {
let desired: String = matches.value_of("pattern").map(str::to_string).unwrap_or_default();
let key = vanity::generate_key::<C>(&desired).expect("Key generation failed");
C::print_from_seed(&key.seed);
}
("restore", Some(matches)) => {
let phrase = matches.value_of("seed")
.expect("seed parameter is required; thus it can't be None; qed");
C::print_from_phrase(phrase, password);
},
("query", Some(matches)) => {
let seed_data = matches.value_of("seed")
.expect("seed parameter is required; thus it can't be None; qed");
let seed_data = if seed_data.starts_with("0x") {
&seed_data[2..]
} else {
seed_data
};
let seed_data: Vec<u8> = seed_data.from_hex().expect("seed is not valid hex");
let correct_size = ::std::mem::size_of::<C::Seed>();
if seed_data.len() != correct_size {
panic!("Seed is incorrect size. It must be {} bytes for this cryptography", correct_size);
}
let mut seed = C::Seed::default();
seed.as_mut().copy_from_slice(&seed_data);
C::print_from_seed(&seed);
},
_ => print_usage(&matches),
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = clap::App::from_yaml(yaml).get_matches();
match matches.subcommand() {
("generate", Some(_matches)) => {
let mut seed = [0u8; 32];
OsRng::new().unwrap().fill_bytes(&mut seed[..]);
print_account(&seed);
}
("vanity", Some(matches)) => {
let desired: String = matches.value_of("pattern").map(str::to_string).unwrap_or_default();
let key = vanity::generate_key(&desired).expect("Key generation failed");
println!("Found account with score {}%", key.score);
print_account(&key.seed);
}
("restore", Some(matches)) => {
// This subcommand is probably obsolete, see
// https://github.com/paritytech/substrate/issues/1063
let mut raw_seed = matches.value_of("seed")
.map(str::as_bytes)
.expect("seed parameter is required; thus it can't be None; qed");
if raw_seed.len() > 32 {
raw_seed = &raw_seed[..32];
println!("seed is too long and will be truncated to: {}", HexDisplay::from(&raw_seed));
}
// Copy the raw_seed into a buffer that already contains ' ' 0x20.
// This will effectively get us padding for seeds shorter than 32.
let mut seed = [' ' as u8; 32];
let len = raw_seed.len().min(32);
seed[..len].copy_from_slice(&raw_seed[..len]);
print_account(&seed);
},
_ => print_usage(&matches),
if matches.is_present("ed25519original") {
execute::<OriginalEd25519>(matches)
} else {
execute::<Sr25519>(matches)
}
}
+9 -8
View File
@@ -15,7 +15,7 @@
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
use rand::{rngs::OsRng, RngCore};
use substrate_primitives::ed25519::Pair;
use super::Crypto;
fn good_waypoint(done: u64) -> u64 {
match done {
@@ -38,9 +38,9 @@ fn next_seed(mut seed: [u8; 32]) -> [u8; 32] {
/// A structure used to carry both Pair and seed.
/// This should usually NOT been used. If unsure, use Pair.
pub struct KeyPair {
pub pair: Pair,
pub seed: [u8; 32],
pub(super) struct KeyPair<C: Crypto> {
pub pair: C::Pair,
pub seed: C::Seed,
pub score: usize,
}
@@ -57,7 +57,7 @@ fn calculate_score(_desired: &str, key: &str) -> usize {
0
}
pub fn generate_key(desired: &str) -> Result<KeyPair, &str> {
pub(super) fn generate_key<C: Crypto<Seed=[u8; 32]>>(desired: &str) -> Result<KeyPair<C>, &str> {
if desired.is_empty() {
return Err("Pattern must not be empty");
}
@@ -77,8 +77,8 @@ pub fn generate_key(desired: &str) -> Result<KeyPair, &str> {
OsRng::new().unwrap().fill_bytes(&mut seed[..]);
}
let p = Pair::from_seed(&seed);
let ss58 = p.public().to_ss58check();
let p = C::pair_from_seed(&seed);
let ss58 = C::ss58_from_pair(&p);
let score = calculate_score(&desired, &ss58);
if score > best || desired.len() < 2 {
best = score;
@@ -104,12 +104,13 @@ pub fn generate_key(desired: &str) -> Result<KeyPair, &str> {
#[cfg(test)]
mod tests {
use super::*;
use super::super::OriginalEd25519;
#[cfg(feature = "bench")]
use test::Bencher;
#[test]
fn test_generation_with_single_char() {
assert!(generate_key("j").unwrap().pair.public().to_ss58check().contains("j"));
assert!(generate_key::<OriginalEd25519>("j").unwrap().pair.public().to_ss58check().contains("j"));
}
#[test]