cfxkey/
keypair.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::{math::pubkey_to_public, Address, Error, Public, Secret};
18use cfx_crypto::crypto::keccak::Keccak256;
19use cfx_types::address_util::AddressUtil;
20use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf;
21use secp256k1::{PublicKey, SecretKey, SECP256K1};
22use std::fmt;
23
24pub fn public_to_address(public: &Public, type_nibble: bool) -> Address {
25    let hash = public.keccak256();
26    let mut result = Address::zero();
27    result.as_bytes_mut().copy_from_slice(&hash[12..]);
28    // In Conflux, we reserve the first four bits to indicate the type of the
29    // address. For user address, the first four bits will be 0x1.
30    if type_nibble {
31        result.set_user_account_type_bits();
32    }
33    result
34}
35
36/// Check if the recovered address started with 0x1. If it does, this public key
37/// will have same the address in Conflux Network and Ethereum.
38pub fn is_compatible_public(public: &Public) -> bool {
39    let hash = public.keccak256();
40    let mut result = Address::zero();
41    result.as_bytes_mut().copy_from_slice(&hash[12..]);
42    // In Conflux, we reserve the first four bits to indicate the type of the
43    // address. For user address, the first four bits will be 0x1.
44    result.is_user_account_address()
45}
46
47#[derive(Debug, Clone, PartialEq, DeriveMallocSizeOf)]
48/// secp256k1 key pair
49pub struct KeyPair {
50    secret: Secret,
51    public: Public,
52}
53
54impl fmt::Display for KeyPair {
55    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
56        writeln!(f, "secret:  {:x}", self.secret)?;
57        writeln!(f, "public:  {:x}", self.public)?;
58        write!(f, "address: {:x}", self.address())
59    }
60}
61
62impl KeyPair {
63    /// Create a pair from secret key
64    pub fn from_secret(secret: Secret) -> Result<KeyPair, Error> {
65        let s = SecretKey::from_slice(&secret[..])?;
66        let public =
67            pubkey_to_public(&PublicKey::from_secret_key(SECP256K1, &s));
68        Ok(KeyPair { secret, public })
69    }
70
71    pub fn from_secret_slice(slice: &[u8]) -> Result<KeyPair, Error> {
72        Self::from_secret(Secret::from_unsafe_slice(slice)?)
73    }
74
75    pub fn from_keypair(sec: SecretKey, publ: PublicKey) -> Self {
76        KeyPair {
77            secret: Secret::from(sec),
78            public: pubkey_to_public(&publ),
79        }
80    }
81
82    pub fn secret(&self) -> &Secret { &self.secret }
83
84    pub fn public(&self) -> &Public { &self.public }
85
86    pub fn address(&self) -> Address { public_to_address(&self.public, true) }
87
88    pub fn evm_address(&self) -> Address {
89        public_to_address(&self.public, false)
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use crate::{KeyPair, Secret};
96    use std::str::FromStr;
97
98    #[test]
99    fn from_secret() {
100        let secret = Secret::from_str(
101            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
102        )
103        .unwrap();
104        let _ = KeyPair::from_secret(secret).unwrap();
105    }
106
107    #[test]
108    fn keypair_display() {
109        let expected =
110"secret:  a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65
111public:  8ce0db0b0359ffc5866ba61903cc2518c3675ef2cf380a7e54bde7ea20e6fa1ab45b7617346cd11b7610001ee6ae5b0155c41cad9527cbcdff44ec67848943a4
112address: 1b073e9233944b5e729e46d618f0d8edf3d9c34a".to_owned();
113        let secret = Secret::from_str(
114            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
115        )
116        .unwrap();
117        let kp = KeyPair::from_secret(secret).unwrap();
118        assert_eq!(format!("{}", kp), expected);
119    }
120}