1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam 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
// Moonbeam 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 Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! The Ethereum Signature implementation.
18
//!
19
//! It includes the Verify and IdentifyAccount traits for the AccountId20
20

            
21
#![cfg_attr(not(feature = "std"), no_std)]
22

            
23
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
24
use scale_info::TypeInfo;
25
use sha3::{Digest, Keccak256};
26
use sp_core::{ecdsa, H160};
27

            
28
pub use serde::{de::DeserializeOwned, Deserialize, Serialize};
29

            
30
//TODO Maybe this should be upstreamed into Frontier (And renamed accordingly) so that it can
31
// be used in palletEVM as well. It may also need more traits such as AsRef, AsMut, etc like
32
// AccountId32 has.
33

            
34
/// System account size in bytes = Pallet_Name_Hash (16) + Storage_name_hash (16) +
35
/// Blake2_128Concat (16) + AccountId (20) + AccountInfo (4 + 12 + AccountData (4* 16)) = 148
36
pub const SYSTEM_ACCOUNT_SIZE: u64 = 148;
37

            
38
/// The account type to be used in Moonbeam. It is a wrapper for 20 fixed bytes. We prefer to use
39
/// a dedicated type to prevent using arbitrary 20 byte arrays were AccountIds are expected. With
40
/// the introduction of the `scale-info` crate this benefit extends even to non-Rust tools like
41
/// Polkadot JS.
42

            
43
#[derive(
44
	Eq,
45
	PartialEq,
46
	Copy,
47
	Clone,
48
	Encode,
49
	Decode,
50
72
	TypeInfo,
51
	MaxEncodedLen,
52
	Default,
53
	PartialOrd,
54
	Ord,
55
	DecodeWithMemTracking,
56
)]
57
pub struct AccountId20(pub [u8; 20]);
58

            
59
impl_serde::impl_fixed_hash_serde!(AccountId20, 20);
60

            
61
#[cfg(feature = "std")]
62
impl std::fmt::Display for AccountId20 {
63
	//TODO This is a pretty quck-n-dirty implementation. Perhaps we should add
64
	// checksum casing here? I bet there is a crate for that.
65
	// Maybe this one https://github.com/miguelmota/rust-eth-checksum
66
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
67
		write!(f, "{:?}", self.0)
68
	}
69
}
70

            
71
impl core::fmt::Debug for AccountId20 {
72
667
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
73
667
		write!(f, "{:?}", H160(self.0))
74
667
	}
75
}
76

            
77
impl From<[u8; 20]> for AccountId20 {
78
37336
	fn from(bytes: [u8; 20]) -> Self {
79
37336
		Self(bytes)
80
37336
	}
81
}
82

            
83
impl From<AccountId20> for [u8; 20] {
84
3150
	fn from(value: AccountId20) -> Self {
85
3150
		value.0
86
3150
	}
87
}
88

            
89
// NOTE: the implementation is lossy, and is intended to be used
90
// only to convert from Polkadot accounts to AccountId20.
91
// See https://github.com/moonbeam-foundation/moonbeam/pull/2315#discussion_r1205830577
92
// DO NOT USE IT FOR ANYTHING ELSE.
93
impl From<[u8; 32]> for AccountId20 {
94
1288
	fn from(bytes: [u8; 32]) -> Self {
95
1288
		let mut buffer = [0u8; 20];
96
1288
		buffer.copy_from_slice(&bytes[..20]);
97
1288
		Self(buffer)
98
1288
	}
99
}
100
impl From<sp_runtime::AccountId32> for AccountId20 {
101
	fn from(account: sp_runtime::AccountId32) -> Self {
102
		let bytes: &[u8; 32] = account.as_ref();
103
		Self::from(*bytes)
104
	}
105
}
106

            
107
impl From<H160> for AccountId20 {
108
104789
	fn from(h160: H160) -> Self {
109
104789
		Self(h160.0)
110
104789
	}
111
}
112

            
113
impl From<AccountId20> for H160 {
114
30439
	fn from(value: AccountId20) -> Self {
115
30439
		H160(value.0)
116
30439
	}
117
}
118

            
119
#[cfg(feature = "std")]
120
impl std::str::FromStr for AccountId20 {
121
	type Err = &'static str;
122
	fn from_str(input: &str) -> Result<Self, Self::Err> {
123
		H160::from_str(input)
124
			.map(Into::into)
125
			.map_err(|_| "invalid hex address.")
126
	}
127
}
128

            
129
#[derive(
130
	Eq,
131
	PartialEq,
132
	Clone,
133
	Encode,
134
	Decode,
135
	sp_core::RuntimeDebug,
136
72
	TypeInfo,
137
	Serialize,
138
	Deserialize,
139
	DecodeWithMemTracking,
140
)]
141
pub struct EthereumSignature(ecdsa::Signature);
142

            
143
impl From<ecdsa::Signature> for EthereumSignature {
144
	fn from(x: ecdsa::Signature) -> Self {
145
		EthereumSignature(x)
146
	}
147
}
148

            
149
impl From<sp_runtime::MultiSignature> for EthereumSignature {
150
	fn from(signature: sp_runtime::MultiSignature) -> Self {
151
		match signature {
152
			sp_runtime::MultiSignature::Ed25519(_) => {
153
				panic!("Ed25519 not supported for EthereumSignature")
154
			}
155
			sp_runtime::MultiSignature::Sr25519(_) => {
156
				panic!("Sr25519 not supported for EthereumSignature")
157
			}
158
			sp_runtime::MultiSignature::Ecdsa(sig) => Self(sig),
159
		}
160
	}
161
}
162

            
163
impl sp_runtime::traits::Verify for EthereumSignature {
164
	type Signer = EthereumSigner;
165
	fn verify<L: sp_runtime::traits::Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId20) -> bool {
166
		let mut m = [0u8; 32];
167
		m.copy_from_slice(Keccak256::digest(msg.get()).as_slice());
168
		match sp_io::crypto::secp256k1_ecdsa_recover(self.0.as_ref(), &m) {
169
			Ok(pubkey) => {
170
				AccountId20(H160::from_slice(&Keccak256::digest(pubkey).as_slice()[12..32]).0)
171
					== *signer
172
			}
173
			Err(sp_io::EcdsaVerifyError::BadRS) => {
174
				log::error!(target: "evm", "Error recovering: Incorrect value of R or S");
175
				false
176
			}
177
			Err(sp_io::EcdsaVerifyError::BadV) => {
178
				log::error!(target: "evm", "Error recovering: Incorrect value of V");
179
				false
180
			}
181
			Err(sp_io::EcdsaVerifyError::BadSignature) => {
182
				log::error!(target: "evm", "Error recovering: Invalid signature");
183
				false
184
			}
185
		}
186
	}
187
}
188

            
189
/// Public key for an Ethereum / Moonbeam compatible account
190
#[derive(
191
	Eq,
192
	PartialEq,
193
	Ord,
194
	PartialOrd,
195
	Clone,
196
	Encode,
197
	Decode,
198
	sp_core::RuntimeDebug,
199
	TypeInfo,
200
	DecodeWithMemTracking,
201
)]
202
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
203
pub struct EthereumSigner([u8; 20]);
204

            
205
impl sp_runtime::traits::IdentifyAccount for EthereumSigner {
206
	type AccountId = AccountId20;
207
2
	fn into_account(self) -> AccountId20 {
208
2
		AccountId20(self.0)
209
2
	}
210
}
211

            
212
impl From<[u8; 20]> for EthereumSigner {
213
	fn from(x: [u8; 20]) -> Self {
214
		EthereumSigner(x)
215
	}
216
}
217

            
218
impl From<ecdsa::Public> for EthereumSigner {
219
2
	fn from(x: ecdsa::Public) -> Self {
220
2
		let decompressed = libsecp256k1::PublicKey::parse_slice(
221
2
			&x.0,
222
2
			Some(libsecp256k1::PublicKeyFormat::Compressed),
223
2
		)
224
2
		.expect("Wrong compressed public key provided")
225
2
		.serialize();
226
2
		let mut m = [0u8; 64];
227
2
		m.copy_from_slice(&decompressed[1..65]);
228
2
		let account = H160::from_slice(&Keccak256::digest(m).as_slice()[12..32]);
229
2
		EthereumSigner(account.into())
230
2
	}
231
}
232

            
233
impl From<libsecp256k1::PublicKey> for EthereumSigner {
234
	fn from(x: libsecp256k1::PublicKey) -> Self {
235
		let mut m = [0u8; 64];
236
		m.copy_from_slice(&x.serialize()[1..65]);
237
		let account = H160::from_slice(&Keccak256::digest(m).as_slice()[12..32]);
238
		EthereumSigner(account.into())
239
	}
240
}
241

            
242
#[cfg(feature = "std")]
243
impl std::fmt::Display for EthereumSigner {
244
	fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
245
		write!(fmt, "ethereum signature: {:?}", H160::from_slice(&self.0))
246
	}
247
}
248

            
249
#[cfg(test)]
250
mod tests {
251
	use super::*;
252
	use sp_core::{ecdsa, Pair, H256};
253
	use sp_runtime::traits::IdentifyAccount;
254

            
255
	#[test]
256
1
	fn test_account_derivation_1() {
257
1
		// Test from https://asecuritysite.com/encryption/ethadd
258
1
		let secret_key =
259
1
			hex::decode("502f97299c472b88754accd412b7c9a6062ef3186fba0c0388365e1edec24875")
260
1
				.unwrap();
261
1
		let mut expected_hex_account = [0u8; 20];
262
1
		hex::decode_to_slice(
263
1
			"976f8456e4e2034179b284a23c0e0c8f6d3da50c",
264
1
			&mut expected_hex_account,
265
1
		)
266
1
		.expect("example data is 20 bytes of valid hex");
267
1

            
268
1
		let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
269
1
		let account: EthereumSigner = public_key.into();
270
1
		let expected_account = AccountId20::from(expected_hex_account);
271
1
		assert_eq!(account.into_account(), expected_account);
272
1
	}
273
	#[test]
274
1
	fn test_account_derivation_2() {
275
1
		// Test from https://asecuritysite.com/encryption/ethadd
276
1
		let secret_key =
277
1
			hex::decode("0f02ba4d7f83e59eaa32eae9c3c4d99b68ce76decade21cdab7ecce8f4aef81a")
278
1
				.unwrap();
279
1
		let mut expected_hex_account = [0u8; 20];
280
1
		hex::decode_to_slice(
281
1
			"420e9f260b40af7e49440cead3069f8e82a5230f",
282
1
			&mut expected_hex_account,
283
1
		)
284
1
		.expect("example data is 20 bytes of valid hex");
285
1

            
286
1
		let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
287
1
		let account: EthereumSigner = public_key.into();
288
1
		let expected_account = AccountId20::from(expected_hex_account);
289
1
		assert_eq!(account.into_account(), expected_account);
290
1
	}
291
	#[test]
292
1
	fn test_account_derivation_3() {
293
1
		let m = hex::decode("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
294
1
			.unwrap();
295
1
		let old = AccountId20(H160::from(H256::from_slice(Keccak256::digest(&m).as_slice())).0);
296
1
		let new = AccountId20(H160::from_slice(&Keccak256::digest(&m).as_slice()[12..32]).0);
297
1
		assert_eq!(new, old);
298
1
	}
299
}