referrerpolicy=no-referrer-when-downgrade

frame_support/crypto/
ecdsa.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Simple ECDSA secp256k1 API.
19//!
20//! Provides an extension trait for [`sp_core::ecdsa::Public`] to do certain operations.
21
22use sp_core::{crypto::ByteArray, ecdsa::Public};
23
24/// Extension trait for [`Public`] to be used from inside the runtime.
25///
26/// # Note
27///
28/// This is needed because host functions cannot be called from within
29/// `sp_core` due to cyclic dependencies  on `sp_io`.
30pub trait ECDSAExt {
31	/// Returns Ethereum address calculated from this ECDSA public key.
32	fn to_eth_address(&self) -> Result<[u8; 20], ()>;
33}
34
35impl ECDSAExt for Public {
36	fn to_eth_address(&self) -> Result<[u8; 20], ()> {
37		use k256::{elliptic_curve::sec1::ToEncodedPoint, PublicKey};
38
39		PublicKey::from_sec1_bytes(self.as_slice()).map_err(drop).and_then(|pub_key| {
40			// uncompress the key
41			let uncompressed = pub_key.to_encoded_point(false);
42			// convert to ETH address
43			<[u8; 20]>::try_from(
44				sp_io::hashing::keccak_256(&uncompressed.as_bytes()[1..])[12..].as_ref(),
45			)
46			.map_err(drop)
47		})
48	}
49}
50
51#[cfg(test)]
52mod tests {
53	use super::*;
54	use sp_core::{ecdsa, Pair};
55
56	#[test]
57	fn to_eth_address_works() {
58		let pair = ecdsa::Pair::from_string("//Alice//password", None).unwrap();
59		let eth_address = pair.public().to_eth_address().unwrap();
60		assert_eq!(
61			array_bytes::bytes2hex("0x", &eth_address),
62			"0xdc1cce4263956850a3c8eb349dc6fc3f7792cb27"
63		);
64	}
65}