referrerpolicy=no-referrer-when-downgrade

pallet_revive/precompiles/builtin/
blake2f.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};
25use sp_runtime::DispatchError;
26
27pub struct Blake2F<T>(PhantomData<T>);
28
29impl<T: Config> PrimitivePrecompile for Blake2F<T> {
30	type T = T;
31	const MATCHER: BuiltinAddressMatcher = BuiltinAddressMatcher::Fixed(NonZero::new(9).unwrap());
32	const HAS_CONTRACT_INFO: bool = false;
33
34	fn call(
35		_address: &[u8; 20],
36		input: Vec<u8>,
37		env: &mut impl Ext<T = Self::T>,
38	) -> Result<Vec<u8>, Error> {
39		const BLAKE2_F_ARG_LEN: usize = 213;
40
41		if input.len() != BLAKE2_F_ARG_LEN {
42			Err(DispatchError::from("invalid input length"))?;
43		}
44
45		let mut rounds_buf: [u8; 4] = [0; 4];
46		rounds_buf.copy_from_slice(&input[0..4]);
47		let rounds: u32 = u32::from_be_bytes(rounds_buf);
48
49		env.gas_meter_mut().charge(RuntimeCosts::Blake2F(rounds))?;
50
51		// we use from_le_bytes below to effectively swap byte order to LE if architecture is BE
52
53		let mut h_buf: [u8; 64] = [0; 64];
54		h_buf.copy_from_slice(&input[4..68]);
55		let mut h = [0u64; 8];
56		let mut ctr = 0;
57		for state_word in &mut h {
58			let mut temp: [u8; 8] = Default::default();
59			temp.copy_from_slice(&h_buf[(ctr * 8)..(ctr + 1) * 8]);
60			*state_word = u64::from_le_bytes(temp);
61			ctr += 1;
62		}
63
64		let mut m_buf: [u8; 128] = [0; 128];
65		m_buf.copy_from_slice(&input[68..196]);
66		let mut m = [0u64; 16];
67		ctr = 0;
68		for msg_word in &mut m {
69			let mut temp: [u8; 8] = Default::default();
70			temp.copy_from_slice(&m_buf[(ctr * 8)..(ctr + 1) * 8]);
71			*msg_word = u64::from_le_bytes(temp);
72			ctr += 1;
73		}
74
75		let mut t_0_buf: [u8; 8] = [0; 8];
76		t_0_buf.copy_from_slice(&input[196..204]);
77		let t_0 = u64::from_le_bytes(t_0_buf);
78
79		let mut t_1_buf: [u8; 8] = [0; 8];
80		t_1_buf.copy_from_slice(&input[204..212]);
81		let t_1 = u64::from_le_bytes(t_1_buf);
82
83		let f = if input[212] == 1 {
84			true
85		} else if input[212] == 0 {
86			false
87		} else {
88			return Err(DispatchError::from("invalid final flag").into());
89		};
90
91		eip_152::compress(&mut h, m, [t_0, t_1], f, rounds as usize);
92
93		let mut output_buf = [0u8; u64::BITS as usize];
94		for (i, state_word) in h.iter().enumerate() {
95			output_buf[i * 8..(i + 1) * 8].copy_from_slice(&state_word.to_le_bytes());
96		}
97
98		Ok(output_buf.to_vec())
99	}
100}
101
102mod eip_152 {
103	/// The precomputed values for BLAKE2b [from the spec](https://tools.ietf.org/html/rfc7693#section-2.7)
104	/// There are 10 16-byte arrays - one for each round
105	/// the entries are calculated from the sigma constants.
106	const SIGMA: [[usize; 16]; 10] = [
107		[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
108		[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
109		[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
110		[7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
111		[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
112		[2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
113		[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
114		[13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
115		[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
116		[10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
117	];
118
119	/// IV is the initialization vector for BLAKE2b. See https://tools.ietf.org/html/rfc7693#section-2.6
120	/// for details.
121	const IV: [u64; 8] = [
122		0x6a09e667f3bcc908,
123		0xbb67ae8584caa73b,
124		0x3c6ef372fe94f82b,
125		0xa54ff53a5f1d36f1,
126		0x510e527fade682d1,
127		0x9b05688c2b3e6c1f,
128		0x1f83d9abfb41bd6b,
129		0x5be0cd19137e2179,
130	];
131
132	#[inline(always)]
133	/// The G mixing function. See https://tools.ietf.org/html/rfc7693#section-3.1
134	fn g(v: &mut [u64], a: usize, b: usize, c: usize, d: usize, x: u64, y: u64) {
135		v[a] = v[a].wrapping_add(v[b]).wrapping_add(x);
136		v[d] = (v[d] ^ v[a]).rotate_right(32);
137		v[c] = v[c].wrapping_add(v[d]);
138		v[b] = (v[b] ^ v[c]).rotate_right(24);
139		v[a] = v[a].wrapping_add(v[b]).wrapping_add(y);
140		v[d] = (v[d] ^ v[a]).rotate_right(16);
141		v[c] = v[c].wrapping_add(v[d]);
142		v[b] = (v[b] ^ v[c]).rotate_right(63);
143	}
144
145	/// The Blake2 compression function F. See https://tools.ietf.org/html/rfc7693#section-3.2
146	/// Takes as an argument the state vector `h`, message block vector `m`, offset counter `t`,
147	/// final block indicator flag `f`, and number of rounds `rounds`. The state vector provided as
148	/// the first parameter is modified by the function.
149	pub fn compress(h: &mut [u64; 8], m: [u64; 16], t: [u64; 2], f: bool, rounds: usize) {
150		let mut v = [0u64; 16];
151		v[..h.len()].copy_from_slice(h); // First half from state.
152		v[h.len()..].copy_from_slice(&IV); // Second half from IV.
153
154		v[12] ^= t[0];
155		v[13] ^= t[1];
156
157		if f {
158			v[14] = !v[14] // Invert all bits if the last-block-flag is set.
159		}
160		for i in 0..rounds {
161			// Message word selection permutation for this round.
162			let s = &SIGMA[i % 10];
163			g(&mut v, 0, 4, 8, 12, m[s[0]], m[s[1]]);
164			g(&mut v, 1, 5, 9, 13, m[s[2]], m[s[3]]);
165			g(&mut v, 2, 6, 10, 14, m[s[4]], m[s[5]]);
166			g(&mut v, 3, 7, 11, 15, m[s[6]], m[s[7]]);
167
168			g(&mut v, 0, 5, 10, 15, m[s[8]], m[s[9]]);
169			g(&mut v, 1, 6, 11, 12, m[s[10]], m[s[11]]);
170			g(&mut v, 2, 7, 8, 13, m[s[12]], m[s[13]]);
171			g(&mut v, 3, 4, 9, 14, m[s[14]], m[s[15]]);
172		}
173
174		for i in 0..8 {
175			h[i] ^= v[i] ^ v[i + 8];
176		}
177	}
178}
179
180#[cfg(test)]
181mod tests {
182	use super::*;
183	use crate::{
184		precompiles::tests::{run_failure_test_vectors, run_test_vectors},
185		tests::Test,
186	};
187
188	#[test]
189	fn test_blake2f() {
190		run_test_vectors::<Blake2F<Test>>(include_str!("./testdata/9-blake2f.json"));
191		run_failure_test_vectors::<Blake2F<Test>>(include_str!(
192			"./testdata/9-blake2f-failures.json"
193		));
194	}
195}