cfxkey/
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::{Error, KeyPair, KeyPairGenerator, Random};
18
19/// Tries to find keypair with address starting with given prefix.
20pub struct Prefix {
21    prefix: Vec<u8>,
22    iterations: usize,
23}
24
25impl Prefix {
26    pub fn new(prefix: Vec<u8>, iterations: usize) -> Self {
27        Prefix { prefix, iterations }
28    }
29}
30
31impl KeyPairGenerator for Prefix {
32    type Error = Error;
33
34    fn generate(&mut self) -> Result<KeyPair, Error> {
35        for _ in 0..self.iterations {
36            let keypair = Random.generate()?;
37
38            if self.prefix.is_empty() {
39                return Ok(keypair);
40            }
41            if keypair.address().as_ref().starts_with(&self.prefix) {
42                return Ok(keypair);
43            }
44        }
45
46        Err(Error::Custom("Could not find keypair".into()))
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use crate::{KeyPairGenerator, Prefix};
53
54    #[test]
55    fn prefix_generator() {
56        let prefix = vec![0x1fu8];
57        let keypair = Prefix::new(prefix.clone(), usize::max_value())
58            .generate()
59            .unwrap();
60        assert!(keypair.address().as_bytes().starts_with(&prefix));
61    }
62}