pallet_evm_precompile_sr25519/
lib.rs

1// This file is part of Astar.
2
3// Copyright (C) Stake Technologies Pte.Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later
5
6// Astar is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// Astar is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with Astar. If not, see <http://www.gnu.org/licenses/>.
18
19#![cfg_attr(not(feature = "std"), no_std)]
20
21use fp_evm::PrecompileHandle;
22use sp_core::{crypto::UncheckedFrom, sr25519, H256};
23use sp_core::{ByteArray, ConstU32};
24use sp_std::marker::PhantomData;
25
26use precompile_utils::prelude::*;
27
28#[cfg(test)]
29mod mock;
30#[cfg(test)]
31mod tests;
32
33// SR25519 signature bytes
34type SR25519SignatureBytes = ConstU32<64>;
35
36/// A precompile to wrap substrate sr25519 functions.
37pub struct Sr25519Precompile<Runtime>(PhantomData<Runtime>);
38
39#[precompile_utils::precompile]
40impl<Runtime: pallet_evm::Config> Sr25519Precompile<Runtime> {
41    #[precompile::public("verify(bytes32,bytes,bytes)")]
42    #[precompile::view]
43    fn verify(
44        _: &mut impl PrecompileHandle,
45        public: H256,
46        signature: BoundedBytes<SR25519SignatureBytes>,
47        message: UnboundedBytes,
48    ) -> EvmResult<bool> {
49        // Parse pub key
50        let public = sr25519::Public::unchecked_from(public);
51        // Parse signature
52        let signature = if let Ok(sig) = sr25519::Signature::from_slice(signature.as_bytes()) {
53            sig
54        } else {
55            // Return `false` if signature length is wrong
56            return Ok(false);
57        };
58
59        log::trace!(
60            target: "sr25519-precompile",
61            "Verify signature {signature:?} for public {public:?} and message {message:?}",
62        );
63
64        let is_confirmed = sp_io::crypto::sr25519_verify(&signature, message.as_bytes(), &public);
65
66        log::trace!(
67            target: "sr25519-precompile",
68            "Verified signature {signature:?} is {is_confirmed:?}",
69        );
70
71        Ok(is_confirmed)
72    }
73}