1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#![cfg_attr(not(feature = "std"), no_std)]

use parity_scale_codec::{Decode, Encode, MaxEncodedLen};
use scale_info::TypeInfo;
// Substrate
use sp_core::{ecdsa, RuntimeDebug, H160, H256};
use sp_io::hashing::keccak_256;
use sp_runtime_interface::pass_by::PassByInner;

/// A fully Ethereum-compatible `AccountId`.
/// Conforms to H160 address and ECDSA key standards.
/// Alternative to H256->H160 mapping.
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default, Hash)]
#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]
pub struct AccountId20(pub [u8; 20]);

#[cfg(feature = "serde")]
impl_serde::impl_fixed_hash_serde!(AccountId20, 20);

#[cfg(feature = "std")]
impl std::str::FromStr for AccountId20 {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        H160::from_str(s)
            .map(Into::into)
            .map_err(|_| "invalid hex address.")
    }
}

#[cfg(feature = "std")]
impl std::fmt::Display for AccountId20 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let address = hex::encode(self.0).trim_start_matches("0x").to_lowercase();
        let address_hash = hex::encode(keccak_256(address.as_bytes()));

        let checksum: String =
            address
                .char_indices()
                .fold(String::from("0x"), |mut acc, (index, address_char)| {
                    let n = u16::from_str_radix(&address_hash[index..index.saturating_add(1)], 16)
                        .expect("Keccak256 hashed; qed");

                    if n > 7 {
                        // make char uppercase if ith character is 9..f
                        acc.push_str(&address_char.to_uppercase().to_string())
                    } else {
                        // already lowercased
                        acc.push(address_char)
                    }

                    acc
                });
        write!(f, "{checksum}")
    }
}

impl sp_std::fmt::Debug for AccountId20 {
    fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result {
        write!(f, "{:?}", H160(self.0))
    }
}

impl From<[u8; 20]> for AccountId20 {
    fn from(bytes: [u8; 20]) -> Self {
        Self(bytes)
    }
}

impl<'a> TryFrom<&'a [u8]> for AccountId20 {
    type Error = ();
    fn try_from(x: &'a [u8]) -> Result<AccountId20, ()> {
        if x.len() == 20 {
            let mut data = [0; 20];
            data.copy_from_slice(x);
            Ok(AccountId20(data))
        } else {
            Err(())
        }
    }
}

impl From<AccountId20> for [u8; 20] {
    fn from(val: AccountId20) -> Self {
        val.0
    }
}

impl From<H160> for AccountId20 {
    fn from(h160: H160) -> Self {
        Self(h160.0)
    }
}

impl From<AccountId20> for H160 {
    fn from(val: AccountId20) -> Self {
        H160(val.0)
    }
}

impl AsRef<[u8]> for AccountId20 {
    fn as_ref(&self) -> &[u8] {
        &self.0[..]
    }
}

impl AsMut<[u8]> for AccountId20 {
    fn as_mut(&mut self) -> &mut [u8] {
        &mut self.0[..]
    }
}

impl AsRef<[u8; 20]> for AccountId20 {
    fn as_ref(&self) -> &[u8; 20] {
        &self.0
    }
}

impl AsMut<[u8; 20]> for AccountId20 {
    fn as_mut(&mut self) -> &mut [u8; 20] {
        &mut self.0
    }
}

impl From<sp_std::vec::Vec<u8>> for AccountId20 {
    fn from(bytes: sp_std::vec::Vec<u8>) -> Self {
        if bytes.len() == 20 {
            let mut data = [0; 20];
            data.copy_from_slice(&bytes);
            AccountId20(data)
        } else if bytes.len() == 22 {
            assert!(bytes.starts_with(b"0x"), "Invalid Prefix");
            let mut data = [0; 20];
            data.copy_from_slice(&bytes[2..]);
            AccountId20(data)
        } else  {
            // Handle the error case, e.g., return a default value or panic
            panic!("Invalid length for AccountId20 bytes");
        }
    }
}


impl From<ecdsa::Public> for AccountId20 {
    fn from(pk: ecdsa::Public) -> Self {
        let decompressed = libsecp256k1::PublicKey::parse_compressed(&pk.0)
            .expect("Wrong compressed public key provided")
            .serialize();
        let mut m = [0u8; 64];
        m.copy_from_slice(&decompressed[1..65]);
        let account = H160::from(H256::from(keccak_256(&m)));
        Self(account.into())
    }
}

// impl From<[u8; 32]> for AccountId20 {
//     fn from(bytes: [u8; 32]) -> Self {
//         let mut buffer = [0u8; 20];
//         buffer.copy_from_slice(&bytes[..20]);
//         Self(buffer)
//     }
// }

#[derive(Eq, PartialEq, Clone, RuntimeDebug, Encode, Decode, TypeInfo)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct EthereumSignature(ecdsa::Signature);

impl sp_runtime::traits::Verify for EthereumSignature {
    type Signer = EthereumSigner;
    fn verify<L: sp_runtime::traits::Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId20) -> bool {
        let m = keccak_256(msg.get());
        match sp_io::crypto::secp256k1_ecdsa_recover(self.0.as_ref(), &m) {
            Ok(pubkey) => AccountId20(H160::from(H256::from(keccak_256(&pubkey))).0) == *signer,
            Err(sp_io::EcdsaVerifyError::BadRS) => {
                log::error!(target: "evm", "Error recovering: Incorrect value of R or S");
                false
            }
            Err(sp_io::EcdsaVerifyError::BadV) => {
                log::error!(target: "evm", "Error recovering: Incorrect value of V");
                false
            }
            Err(sp_io::EcdsaVerifyError::BadSignature) => {
                log::error!(target: "evm", "Error recovering: Invalid signature");
                false
            }
        }
    }
}

impl EthereumSignature {
    pub fn new(s: ecdsa::Signature) -> Self {
        EthereumSignature(s)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[derive(RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo, PassByInner)]
pub struct EthereumSigner([u8; 20]);

impl From<[u8; 20]> for EthereumSigner {
    fn from(x: [u8; 20]) -> Self {
        EthereumSigner(x)
    }
}

impl sp_runtime::traits::IdentifyAccount for EthereumSigner {
    type AccountId = AccountId20;
    fn into_account(self) -> AccountId20 {
        AccountId20(self.0)
    }
}

#[cfg(feature = "std")]
impl std::fmt::Display for EthereumSigner {
    fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "{:?}", H160::from(self.0))
    }
}

impl From<ecdsa::Public> for EthereumSigner {
    fn from(pk: ecdsa::Public) -> Self {
        let decompressed = libsecp256k1::PublicKey::parse_compressed(&pk.0)
            .expect("Wrong compressed public key provided")
            .serialize();
        let mut m = [0u8; 64];
        m.copy_from_slice(&decompressed[1..65]);
        let account = H160::from(H256::from(keccak_256(&m)));
        EthereumSigner(account.into())
    }
}