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, 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
685
	Eq, PartialEq, Copy, Clone, Encode, Decode, TypeInfo, MaxEncodedLen, Default, PartialOrd, Ord,
45
)]
46
pub struct AccountId20(pub [u8; 20]);
47

            
48
impl_serde::impl_fixed_hash_serde!(AccountId20, 20);
49

            
50
#[cfg(feature = "std")]
51
impl std::fmt::Display for AccountId20 {
52
	//TODO This is a pretty quck-n-dirty implementation. Perhaps we should add
53
	// checksum casing here? I bet there is a crate for that.
54
	// Maybe this one https://github.com/miguelmota/rust-eth-checksum
55
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56
		write!(f, "{:?}", self.0)
57
	}
58
}
59

            
60
impl core::fmt::Debug for AccountId20 {
61
572
	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62
572
		write!(f, "{:?}", H160(self.0))
63
572
	}
64
}
65

            
66
impl From<[u8; 20]> for AccountId20 {
67
3679042
	fn from(bytes: [u8; 20]) -> Self {
68
3679042
		Self(bytes)
69
3679042
	}
70
}
71

            
72
impl From<AccountId20> for [u8; 20] {
73
2768
	fn from(value: AccountId20) -> Self {
74
2768
		value.0
75
2768
	}
76
}
77

            
78
// NOTE: the implementation is lossy, and is intended to be used
79
// only to convert from Polkadot accounts to AccountId20.
80
// See https://github.com/moonbeam-foundation/moonbeam/pull/2315#discussion_r1205830577
81
// DO NOT USE IT FOR ANYTHING ELSE.
82
impl From<[u8; 32]> for AccountId20 {
83
1188
	fn from(bytes: [u8; 32]) -> Self {
84
1188
		let mut buffer = [0u8; 20];
85
1188
		buffer.copy_from_slice(&bytes[..20]);
86
1188
		Self(buffer)
87
1188
	}
88
}
89
impl From<sp_runtime::AccountId32> for AccountId20 {
90
	fn from(account: sp_runtime::AccountId32) -> Self {
91
		let bytes: &[u8; 32] = account.as_ref();
92
		Self::from(*bytes)
93
	}
94
}
95

            
96
impl From<H160> for AccountId20 {
97
48730
	fn from(h160: H160) -> Self {
98
48730
		Self(h160.0)
99
48730
	}
100
}
101

            
102
impl From<AccountId20> for H160 {
103
4892870
	fn from(value: AccountId20) -> Self {
104
4892870
		H160(value.0)
105
4892870
	}
106
}
107

            
108
#[cfg(feature = "std")]
109
impl std::str::FromStr for AccountId20 {
110
	type Err = &'static str;
111
	fn from_str(input: &str) -> Result<Self, Self::Err> {
112
		H160::from_str(input)
113
			.map(Into::into)
114
			.map_err(|_| "invalid hex address.")
115
	}
116
}
117

            
118
#[derive(
119
69
	Eq, PartialEq, Clone, Encode, Decode, sp_core::RuntimeDebug, TypeInfo, Serialize, Deserialize,
120
)]
121
pub struct EthereumSignature(ecdsa::Signature);
122

            
123
impl From<ecdsa::Signature> for EthereumSignature {
124
	fn from(x: ecdsa::Signature) -> Self {
125
		EthereumSignature(x)
126
	}
127
}
128

            
129
impl From<sp_runtime::MultiSignature> for EthereumSignature {
130
	fn from(signature: sp_runtime::MultiSignature) -> Self {
131
		match signature {
132
			sp_runtime::MultiSignature::Ed25519(_) => {
133
				panic!("Ed25519 not supported for EthereumSignature")
134
			}
135
			sp_runtime::MultiSignature::Sr25519(_) => {
136
				panic!("Sr25519 not supported for EthereumSignature")
137
			}
138
			sp_runtime::MultiSignature::Ecdsa(sig) => Self(sig),
139
		}
140
	}
141
}
142

            
143
impl sp_runtime::traits::Verify for EthereumSignature {
144
	type Signer = EthereumSigner;
145
	fn verify<L: sp_runtime::traits::Lazy<[u8]>>(&self, mut msg: L, signer: &AccountId20) -> bool {
146
		let mut m = [0u8; 32];
147
		m.copy_from_slice(Keccak256::digest(msg.get()).as_slice());
148
		match sp_io::crypto::secp256k1_ecdsa_recover(self.0.as_ref(), &m) {
149
			Ok(pubkey) => {
150
				AccountId20(H160::from_slice(&Keccak256::digest(pubkey).as_slice()[12..32]).0)
151
					== *signer
152
			}
153
			Err(sp_io::EcdsaVerifyError::BadRS) => {
154
				log::error!(target: "evm", "Error recovering: Incorrect value of R or S");
155
				false
156
			}
157
			Err(sp_io::EcdsaVerifyError::BadV) => {
158
				log::error!(target: "evm", "Error recovering: Incorrect value of V");
159
				false
160
			}
161
			Err(sp_io::EcdsaVerifyError::BadSignature) => {
162
				log::error!(target: "evm", "Error recovering: Invalid signature");
163
				false
164
			}
165
		}
166
	}
167
}
168

            
169
/// Public key for an Ethereum / Moonbeam compatible account
170
#[derive(
171
	Eq, PartialEq, Ord, PartialOrd, Clone, Encode, Decode, sp_core::RuntimeDebug, TypeInfo,
172
)]
173
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
174
pub struct EthereumSigner([u8; 20]);
175

            
176
impl sp_runtime::traits::IdentifyAccount for EthereumSigner {
177
	type AccountId = AccountId20;
178
2
	fn into_account(self) -> AccountId20 {
179
2
		AccountId20(self.0)
180
2
	}
181
}
182

            
183
impl From<[u8; 20]> for EthereumSigner {
184
	fn from(x: [u8; 20]) -> Self {
185
		EthereumSigner(x)
186
	}
187
}
188

            
189
impl From<ecdsa::Public> for EthereumSigner {
190
2
	fn from(x: ecdsa::Public) -> Self {
191
2
		let decompressed = libsecp256k1::PublicKey::parse_slice(
192
2
			&x.0,
193
2
			Some(libsecp256k1::PublicKeyFormat::Compressed),
194
2
		)
195
2
		.expect("Wrong compressed public key provided")
196
2
		.serialize();
197
2
		let mut m = [0u8; 64];
198
2
		m.copy_from_slice(&decompressed[1..65]);
199
2
		let account = H160::from_slice(&Keccak256::digest(m).as_slice()[12..32]);
200
2
		EthereumSigner(account.into())
201
2
	}
202
}
203

            
204
impl From<libsecp256k1::PublicKey> for EthereumSigner {
205
	fn from(x: libsecp256k1::PublicKey) -> Self {
206
		let mut m = [0u8; 64];
207
		m.copy_from_slice(&x.serialize()[1..65]);
208
		let account = H160::from_slice(&Keccak256::digest(m).as_slice()[12..32]);
209
		EthereumSigner(account.into())
210
	}
211
}
212

            
213
#[cfg(feature = "std")]
214
impl std::fmt::Display for EthereumSigner {
215
	fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
216
		write!(fmt, "ethereum signature: {:?}", H160::from_slice(&self.0))
217
	}
218
}
219

            
220
#[cfg(test)]
221
mod tests {
222
	use super::*;
223
	use sp_core::{ecdsa, Pair, H256};
224
	use sp_runtime::traits::IdentifyAccount;
225

            
226
	#[test]
227
1
	fn test_account_derivation_1() {
228
1
		// Test from https://asecuritysite.com/encryption/ethadd
229
1
		let secret_key =
230
1
			hex::decode("502f97299c472b88754accd412b7c9a6062ef3186fba0c0388365e1edec24875")
231
1
				.unwrap();
232
1
		let mut expected_hex_account = [0u8; 20];
233
1
		hex::decode_to_slice(
234
1
			"976f8456e4e2034179b284a23c0e0c8f6d3da50c",
235
1
			&mut expected_hex_account,
236
1
		)
237
1
		.expect("example data is 20 bytes of valid hex");
238
1

            
239
1
		let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
240
1
		let account: EthereumSigner = public_key.into();
241
1
		let expected_account = AccountId20::from(expected_hex_account);
242
1
		assert_eq!(account.into_account(), expected_account);
243
1
	}
244
	#[test]
245
1
	fn test_account_derivation_2() {
246
1
		// Test from https://asecuritysite.com/encryption/ethadd
247
1
		let secret_key =
248
1
			hex::decode("0f02ba4d7f83e59eaa32eae9c3c4d99b68ce76decade21cdab7ecce8f4aef81a")
249
1
				.unwrap();
250
1
		let mut expected_hex_account = [0u8; 20];
251
1
		hex::decode_to_slice(
252
1
			"420e9f260b40af7e49440cead3069f8e82a5230f",
253
1
			&mut expected_hex_account,
254
1
		)
255
1
		.expect("example data is 20 bytes of valid hex");
256
1

            
257
1
		let public_key = ecdsa::Pair::from_seed_slice(&secret_key).unwrap().public();
258
1
		let account: EthereumSigner = public_key.into();
259
1
		let expected_account = AccountId20::from(expected_hex_account);
260
1
		assert_eq!(account.into_account(), expected_account);
261
1
	}
262
	#[test]
263
1
	fn test_account_derivation_3() {
264
1
		let m = hex::decode("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470")
265
1
			.unwrap();
266
1
		let old = AccountId20(H160::from(H256::from_slice(Keccak256::digest(&m).as_slice())).0);
267
1
		let new = AccountId20(H160::from_slice(&Keccak256::digest(&m).as_slice()[12..32]).0);
268
1
		assert_eq!(new, old);
269
1
	}
270
}