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(Clone, PartialEq, DeriveMallocSizeOf)]
48/// secp256k1 key pair
49pub struct KeyPair {
50    secret: Secret,
51    public: Public,
52}
53
54impl fmt::Debug for KeyPair {
55    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56        f.debug_struct("KeyPair")
57            .field("secret", &self.secret)
58            .field("public", &self.public)
59            .finish()
60    }
61}
62
63impl fmt::Display for KeyPair {
64    fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
65        writeln!(f, "secret:  {}", self.secret)?;
66        writeln!(f, "public:  {:x}", self.public)?;
67        write!(f, "address: {:x}", self.address())
68    }
69}
70
71impl KeyPair {
72    /// Create a pair from secret key
73    pub fn from_secret(secret: Secret) -> Result<KeyPair, Error> {
74        let s = SecretKey::from_slice(&secret[..])?;
75        let public =
76            pubkey_to_public(&PublicKey::from_secret_key(SECP256K1, &s));
77        Ok(KeyPair { secret, public })
78    }
79
80    pub fn from_secret_slice(slice: &[u8]) -> Result<KeyPair, Error> {
81        Self::from_secret(Secret::from_unsafe_slice(slice)?)
82    }
83
84    pub fn from_keypair(sec: SecretKey, publ: PublicKey) -> Self {
85        KeyPair {
86            secret: Secret::from(sec),
87            public: pubkey_to_public(&publ),
88        }
89    }
90
91    pub fn secret(&self) -> &Secret { &self.secret }
92
93    pub fn public(&self) -> &Public { &self.public }
94
95    pub fn address(&self) -> Address { public_to_address(&self.public, true) }
96
97    pub fn evm_address(&self) -> Address {
98        public_to_address(&self.public, false)
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use crate::{KeyPair, Secret};
105    use std::str::FromStr;
106
107    #[test]
108    fn from_secret() {
109        let secret = Secret::from_str(
110            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
111        )
112        .unwrap();
113        let _ = KeyPair::from_secret(secret).unwrap();
114    }
115
116    #[test]
117    fn keypair_display() {
118        let expected =
119"secret:  0xa100..3f65
120public:  8ce0db0b0359ffc5866ba61903cc2518c3675ef2cf380a7e54bde7ea20e6fa1ab45b7617346cd11b7610001ee6ae5b0155c41cad9527cbcdff44ec67848943a4
121address: 1b073e9233944b5e729e46d618f0d8edf3d9c34a".to_owned();
122        let secret = Secret::from_str(
123            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
124        )
125        .unwrap();
126        let kp = KeyPair::from_secret(secret).unwrap();
127        assert_eq!(format!("{}", kp), expected);
128    }
129}