Remove nonsense code and options, fix score and generally make subkey work (#936)

* Remove nonsense code and options, fix score and generally make subkey work.

* Rename Demo -> Node
This commit is contained in:
Gav Wood
2018-10-20 22:15:28 +02:00
committed by GitHub
parent e47f3835fd
commit 1475610880
4 changed files with 30 additions and 49 deletions
+1 -1
View File
@@ -490,7 +490,7 @@ macro_rules! construct_simple_service {
/// // Declare the block type /// // Declare the block type
/// Block = Block, /// Block = Block,
/// // Declare the network protocol and give an initializer. /// // Declare the network protocol and give an initializer.
/// NetworkProtocol = DemoProtocol { |config| Ok(DemoProtocol::new()) }, /// NetworkProtocol = NodeProtocol { |config| Ok(NodeProtocol::new()) },
/// RuntimeDispatch = node_executor::Executor, /// RuntimeDispatch = node_executor::Executor,
/// FullTransactionPoolApi = transaction_pool::ChainApi<FullBackend<Self>, FullExecutor<Self>, Block> /// FullTransactionPoolApi = transaction_pool::ChainApi<FullBackend<Self>, FullExecutor<Self>, Block>
/// { |config, client| Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) }, /// { |config, client| Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) },
+2 -2
View File
@@ -22,7 +22,7 @@ use std::sync::Arc;
use transaction_pool::{self, txpool::{Pool as TransactionPool}}; use transaction_pool::{self, txpool::{Pool as TransactionPool}};
use node_primitives::Block; use node_primitives::Block;
use node_runtime::GenesisConfig; use node_runtime::GenesisConfig;
use node_network::Protocol as DemoProtocol; use node_network::Protocol as NodeProtocol;
use substrate_service::{ use substrate_service::{
FactoryFullConfiguration, LightComponents, FullComponents, FullBackend, FactoryFullConfiguration, LightComponents, FullComponents, FullBackend,
LightBackend, FullExecutor, LightExecutor LightBackend, FullExecutor, LightExecutor
@@ -61,7 +61,7 @@ construct_simple_service!(Service);
construct_service_factory! { construct_service_factory! {
struct Factory { struct Factory {
Block = Block, Block = Block,
NetworkProtocol = DemoProtocol { |config| Ok(DemoProtocol::new()) }, NetworkProtocol = NodeProtocol { |config| Ok(NodeProtocol::new()) },
RuntimeDispatch = node_executor::Executor, RuntimeDispatch = node_executor::Executor,
FullTransactionPoolApi = transaction_pool::ChainApi<FullBackend<Self>, FullExecutor<Self>, Block> FullTransactionPoolApi = transaction_pool::ChainApi<FullBackend<Self>, FullExecutor<Self>, Block>
{ |config, client| Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) }, { |config, client| Ok(TransactionPool::new(config, transaction_pool::ChainApi::new(client))) },
+8 -9
View File
@@ -34,18 +34,13 @@ fn main() {
match matches.subcommand() { match matches.subcommand() {
("vanity", Some(matches)) => { ("vanity", Some(matches)) => {
let desired: String = matches.value_of("pattern").map(str::to_string).unwrap_or_default(); let desired: String = matches.value_of("pattern").map(str::to_string).unwrap_or_default();
let amount_of_keys = matches.value_of("number") let key = vanity::generate_key(&desired).expect("Key generation failed");
.expect("`number` has a default value; thus it can't be None; qed"); println!("Seed {} (hex: 0x{}) - {} ({}%)",
let amount_of_keys: usize = amount_of_keys.parse::<usize>().expect("Failed to parse number");
let keys = vanity::generate_key(&desired, amount_of_keys, true).expect("Key generation failed");
for key in keys {
println!("{} - {} ({}%)",
key.pair.public().to_ss58check(), key.pair.public().to_ss58check(),
HexDisplay::from(&key.pair.public().0),
HexDisplay::from(&key.seed), HexDisplay::from(&key.seed),
key.score); key.score);
} }
}
("restore", Some(matches)) => { ("restore", Some(matches)) => {
let mut raw_seed = matches.value_of("seed") let mut raw_seed = matches.value_of("seed")
.map(str::as_bytes) .map(str::as_bytes)
@@ -63,7 +58,11 @@ fn main() {
seed[..len].copy_from_slice(&raw_seed[..len]); seed[..len].copy_from_slice(&raw_seed[..len]);
let pair = Pair::from_seed(&seed); let pair = Pair::from_seed(&seed);
println!("{}: {}", HexDisplay::from(&seed), pair.public().to_ss58check()); println!("Seed 0x{} is account:\n SS58: {}\n Hex: 0x{}",
HexDisplay::from(&seed),
pair.public().to_ss58check(),
HexDisplay::from(&pair.public().0)
);
}, },
_ => print_usage(&matches), _ => print_usage(&matches),
} }
+16 -34
View File
@@ -16,7 +16,6 @@
use rand::{OsRng, Rng}; use rand::{OsRng, Rng};
use substrate_primitives::ed25519::Pair; use substrate_primitives::ed25519::Pair;
use std::cmp;
fn good_waypoint(done: u64) -> u64 { fn good_waypoint(done: u64) -> u64 {
match done { match done {
@@ -52,29 +51,26 @@ fn calculate_score(_desired: &str, key: &str) -> usize {
let snip_size = _desired.len() - truncate; let snip_size = _desired.len() - truncate;
let truncated = &_desired[0..snip_size]; let truncated = &_desired[0..snip_size];
if let Some(pos) = key.find(truncated) { if let Some(pos) = key.find(truncated) {
let score = cmp::min(100, (51 - pos) + (snip_size * 50 / _desired.len())); println!("pos is {} {}", pos, key);
return score; return (47 - pos) + (snip_size * 48);
} }
} }
0 0
} }
pub fn generate_key(_desired: &str, _amount: usize, paranoiac: bool) -> Result<Vec<KeyPair>, &str> { pub fn generate_key(_desired: &str) -> Result<KeyPair, &str> {
println!("Generating {} keys with pattern '{}'", _amount, &_desired); println!("Generating key containing pattern '{}'", _desired);
let top = 30 + (_desired.len() * 32); let top = 45 + (_desired.len() * 48);
let mut best = 0; let mut best = 0;
let mut seed = [0u8; 32]; let mut seed = [0u8; 32];
let mut done = 0; let mut done = 0;
let mut res = vec![];
OsRng::new().unwrap().fill_bytes(&mut seed[..]); OsRng::new().unwrap().fill_bytes(&mut seed[..]);
loop { loop {
if res.len() >= _amount { break; } // reset to a new random seed at beginning and regularly thereafter
if done % 100000 == 0 {
// reset to a new random seed at beginning and regularly after for paranoia.
if paranoiac || done % 100000 == 0 {
OsRng::new().unwrap().fill_bytes(&mut seed[..]); OsRng::new().unwrap().fill_bytes(&mut seed[..]);
} }
@@ -88,22 +84,18 @@ pub fn generate_key(_desired: &str, _amount: usize, paranoiac: bool) -> Result<V
seed: seed.clone(), seed: seed.clone(),
score: score, score: score,
}; };
res.push(keypair);
if best == top { if best == top {
println!("best: {} == top: {}", best, top); println!("best: {} == top: {}", best, top);
break; return Ok(keypair);
} }
} }
seed = next_seed(seed); seed = next_seed(seed);
done += 1; done += 1;
if done % good_waypoint(done) == 0 { if done % good_waypoint(done) == 0 {
println!("Stopping after {} keys searched", done); println!("{} keys searched", done);
break;
} }
} }
res.sort_unstable_by(|a, b| b.score.cmp(&a.score));
Ok(res)
} }
#[cfg(test)] #[cfg(test)]
@@ -112,49 +104,39 @@ mod tests {
#[cfg(feature = "bench")] #[cfg(feature = "bench")]
use test::Bencher; use test::Bencher;
#[test]
fn test_generation_no_args() {
assert!(generate_key("",1, false).unwrap().len() == 1);
}
#[test] #[test]
fn test_generation_with_single_char() { fn test_generation_with_single_char() {
assert!(generate_key("j", 1, false).unwrap().len() == 1); assert!(generate_key("j").unwrap().pair.public().to_ss58check().contains("j"));
}
#[test]
fn test_generation_with_args() {
assert!(generate_key("polka", 2, false).unwrap().len() == 2);
} }
#[test] #[test]
fn test_score_1_char_100() { fn test_score_1_char_100() {
let score = calculate_score("j", "5jolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"); let score = calculate_score("j", "5jolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim");
assert!(score == 100, format!("Wrong score, we found {}", score)); assert_eq!(score, 94);
} }
#[test] #[test]
fn test_score_100() { fn test_score_100() {
let score = calculate_score("Polkadot", "5PolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"); let score = calculate_score("Polkadot", "5PolkadotwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim");
assert!( score == 100, format!("Wrong score, we found {}", score)); assert_eq!(score, 430);
} }
#[test] #[test]
fn test_score_50_2() { fn test_score_50_2() {
// 50% for the position + 50% for the size // 50% for the position + 50% for the size
assert!(calculate_score("Polkadot", "5PolkXXXXwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim") == 75); assert_eq!(calculate_score("Polkadot", "5PolkXXXXwHY5k9GpdTgpqs9xjuNvtv8EcwCFpEeyEf3KHim"), 238);
} }
#[test] #[test]
fn test_score_0() { fn test_score_0() {
assert!(calculate_score("Polkadot", "5GUWv4bLCchGUHJrzULXnh4JgXsMpTKRnjuXTY7Qo1Kh9uYK") == 0); assert_eq!(calculate_score("Polkadot", "5GUWv4bLCchGUHJrzULXnh4JgXsMpTKRnjuXTY7Qo1Kh9uYK"), 0);
} }
#[cfg(feature = "bench")] #[cfg(feature = "bench")]
#[bench] #[bench]
fn bench_paranoiac(b: &mut Bencher) { fn bench_paranoiac(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
generate_key("polka", 3, true) generate_key("polk")
}); });
} }
@@ -162,7 +144,7 @@ mod tests {
#[bench] #[bench]
fn bench_not_paranoiac(b: &mut Bencher) { fn bench_not_paranoiac(b: &mut Bencher) {
b.iter(|| { b.iter(|| {
generate_key("polka", 3, false) generate_key("polk")
}); });
} }
} }