referrerpolicy=no-referrer-when-downgrade

pallet_revive/precompiles/builtin/
sha256.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
18use crate::{
19	precompiles::{BuiltinAddressMatcher, Error, Ext, PrimitivePrecompile},
20	vm::RuntimeCosts,
21	Config,
22};
23use alloc::vec::Vec;
24use core::{marker::PhantomData, num::NonZero};
25
26pub struct Sha256<T>(PhantomData<T>);
27
28impl<T: Config> PrimitivePrecompile for Sha256<T> {
29	type T = T;
30	const MATCHER: BuiltinAddressMatcher = BuiltinAddressMatcher::Fixed(NonZero::new(2).unwrap());
31	const HAS_CONTRACT_INFO: bool = false;
32
33	fn call(
34		_address: &[u8; 20],
35		input: Vec<u8>,
36		env: &mut impl Ext<T = Self::T>,
37	) -> Result<Vec<u8>, Error> {
38		env.gas_meter_mut().charge(RuntimeCosts::HashSha256(input.len() as _))?;
39		let data = sp_io::hashing::sha2_256(&input).to_vec();
40		Ok(data)
41	}
42}
43
44#[cfg(test)]
45mod tests {
46	use super::*;
47	use crate::{precompiles::tests::run_test_vectors, tests::Test};
48
49	#[test]
50	fn test_sha256() {
51		run_test_vectors::<Sha256<Test>>(include_str!("./testdata/2-sha256.json"));
52	}
53}