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::{Address, Error, Public, Secret, SECP256K1};
18use cfx_crypto::crypto::keccak::Keccak256;
19use cfx_types::address_util::AddressUtil;
20use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf;
21use secp256k1::key;
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 context = &SECP256K1;
66        let s: key::SecretKey =
67            key::SecretKey::from_slice(context, &secret[..])?;
68        let pub_key = key::PublicKey::from_secret_key(context, &s)?;
69        let serialized = pub_key.serialize_vec(context, false);
70
71        let mut public = Public::default();
72        public.as_bytes_mut().copy_from_slice(&serialized[1..65]);
73
74        let keypair = KeyPair { secret, public };
75
76        Ok(keypair)
77    }
78
79    pub fn from_secret_slice(slice: &[u8]) -> Result<KeyPair, Error> {
80        Self::from_secret(Secret::from_unsafe_slice(slice)?)
81    }
82
83    pub fn from_keypair(sec: key::SecretKey, publ: key::PublicKey) -> Self {
84        let context = &SECP256K1;
85        let serialized = publ.serialize_vec(context, false);
86        let secret = Secret::from(sec);
87        let mut public = Public::default();
88        public.as_bytes_mut().copy_from_slice(&serialized[1..65]);
89
90        KeyPair { secret, public }
91    }
92
93    pub fn secret(&self) -> &Secret { &self.secret }
94
95    pub fn public(&self) -> &Public { &self.public }
96
97    pub fn address(&self) -> Address { public_to_address(&self.public, true) }
98
99    pub fn evm_address(&self) -> Address {
100        public_to_address(&self.public, false)
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use crate::{KeyPair, Secret};
107    use std::str::FromStr;
108
109    #[test]
110    fn from_secret() {
111        let secret = Secret::from_str(
112            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
113        )
114        .unwrap();
115        let _ = KeyPair::from_secret(secret).unwrap();
116    }
117
118    #[test]
119    fn keypair_display() {
120        let expected =
121"secret:  a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65
122public:  8ce0db0b0359ffc5866ba61903cc2518c3675ef2cf380a7e54bde7ea20e6fa1ab45b7617346cd11b7610001ee6ae5b0155c41cad9527cbcdff44ec67848943a4
123address: 1b073e9233944b5e729e46d618f0d8edf3d9c34a".to_owned();
124        let secret = Secret::from_str(
125            "a100df7a048e50ed308ea696dc600215098141cb391e9527329df289f9383f65",
126        )
127        .unwrap();
128        let kp = KeyPair::from_secret(secret).unwrap();
129        assert_eq!(format!("{}", kp), expected);
130    }
131}