cfxstore/
presale.rs

1// Copyright 2015-2020 Parity Technologies (UK) Ltd.
2// This file is part of OpenEthereum.
3
4// OpenEthereum 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// OpenEthereum 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 OpenEthereum.  If not, see <http://www.gnu.org/licenses/>.
16
17use crate::{json, Error};
18use cfx_crypto::crypto::{aes, keccak::Keccak256, pbkdf2};
19use cfxkey::{Address, KeyPair, Password, Secret};
20use std::{fs, num::NonZeroU32, path::Path};
21
22/// Pre-sale wallet.
23pub struct PresaleWallet {
24    iv: [u8; 16],
25    ciphertext: Vec<u8>,
26    address: Address,
27}
28
29impl From<json::PresaleWallet> for PresaleWallet {
30    fn from(wallet: json::PresaleWallet) -> Self {
31        let mut iv = [0u8; 16];
32        iv.copy_from_slice(&wallet.encseed[..16]);
33
34        let mut ciphertext = vec![];
35        ciphertext.extend_from_slice(&wallet.encseed[16..]);
36
37        let address_bytes: [u8; 20] = wallet.address.into();
38        PresaleWallet {
39            iv,
40            ciphertext,
41            address: Address::from(address_bytes),
42        }
43    }
44}
45
46impl PresaleWallet {
47    /// Open a pre-sale wallet.
48    pub fn open<P>(path: P) -> Result<Self, Error>
49    where P: AsRef<Path> {
50        let file = fs::File::open(path)?;
51        let presale = json::PresaleWallet::load(file)
52            .map_err(|e| Error::InvalidKeyFile(format!("{}", e)))?;
53        Ok(PresaleWallet::from(presale))
54    }
55
56    /// Decrypt the wallet.
57    pub fn decrypt(&self, password: &Password) -> Result<KeyPair, Error> {
58        let mut derived_key = [0u8; 32];
59        let salt = pbkdf2::Salt(password.as_bytes());
60        let sec = pbkdf2::Secret(password.as_bytes());
61        let iter = NonZeroU32::new(2000).expect("2000 > 0; qed");
62        pbkdf2::sha256(iter.get(), salt, sec, &mut derived_key)
63            .map_err(Error::EthCrypto)?;
64
65        let mut key = vec![0; self.ciphertext.len()];
66        let unpadded = aes::decrypt_128_cbc(
67            &derived_key[0..16],
68            &self.iv,
69            &self.ciphertext,
70            &mut key,
71        )
72        .map_err(|_| Error::InvalidPassword)?;
73
74        let secret = Secret::import_key(&unpadded.keccak256())?;
75        let kp = KeyPair::from_secret(secret)?;
76        if kp.evm_address() == self.address {
77            return Ok(kp);
78        }
79
80        Err(Error::InvalidPassword)
81    }
82}
83
84#[cfg(test)]
85mod tests {
86    use super::PresaleWallet;
87    use crate::json;
88
89    #[test]
90    fn test() {
91        let json = r#"
92		{
93			"encseed": "137103c28caeebbcea5d7f95edb97a289ded151b72159137cb7b2671f394f54cff8c121589dcb373e267225547b3c71cbdb54f6e48ec85cd549f96cf0dedb3bc0a9ac6c79b9c426c5878ca2c9d06ff42a23cb648312fc32ba83649de0928e066",
94			"ethaddr": "ede84640d1a1d3e06902048e67aa7db8d52c2ce1",
95			"email": "123@gmail.com",
96			"btcaddr": "1JvqEc6WLhg6GnyrLBe2ztPAU28KRfuseH"
97		} "#;
98
99        let wallet = json::PresaleWallet::load(json.as_bytes()).unwrap();
100        let wallet = PresaleWallet::from(wallet);
101        wallet.decrypt(&"123".into()).unwrap();
102        assert!(wallet.decrypt(&"123".into()).is_ok());
103        assert!(wallet.decrypt(&"124".into()).is_err());
104    }
105}