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