cfxkey/
brain_prefix.rs

1// Copyright 2015-2019 Parity Technologies (UK) Ltd.
2// This file is part of Parity Ethereum.
3
4// Parity Ethereum is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// Parity Ethereum is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.
16
17use super::{Brain, Error, KeyPair, KeyPairGenerator};
18use parity_wordlist as wordlist;
19
20/// Tries to find brain-seed keypair with address starting with given prefix.
21pub struct BrainPrefix {
22    prefix: Vec<u8>,
23    iterations: usize,
24    no_of_words: usize,
25    last_phrase: String,
26}
27
28impl BrainPrefix {
29    pub fn new(prefix: Vec<u8>, iterations: usize, no_of_words: usize) -> Self {
30        BrainPrefix {
31            prefix,
32            iterations,
33            no_of_words,
34            last_phrase: String::new(),
35        }
36    }
37
38    pub fn phrase(&self) -> &str { &self.last_phrase }
39}
40
41impl KeyPairGenerator for BrainPrefix {
42    type Error = Error;
43
44    fn generate(&mut self) -> Result<KeyPair, Error> {
45        for _ in 0..self.iterations {
46            let phrase = wordlist::random_phrase(self.no_of_words);
47            let keypair = Brain::new(phrase.clone()).generate().unwrap();
48
49            if self.prefix.is_empty() {
50                self.last_phrase = phrase;
51                return Ok(keypair);
52            }
53
54            if keypair.address().as_ref().starts_with(&self.prefix) {
55                self.last_phrase = phrase;
56                return Ok(keypair);
57            }
58        }
59        Err(Error::Custom("Could not find keypair".into()))
60    }
61}
62
63#[cfg(test)]
64mod tests {
65    use crate::{BrainPrefix, KeyPairGenerator};
66
67    #[test]
68    fn prefix_generator() {
69        let prefix = vec![0x10u8];
70        let keypair = BrainPrefix::new(prefix.clone(), usize::max_value(), 12)
71            .generate()
72            .unwrap();
73        assert!(keypair.address().as_bytes().starts_with(&prefix));
74    }
75}