Skip to main content

revm_precompile/blake2/
mod.rs

1//! Blake2 precompile. More details in [`run`].
2//!
3//! The compression function is vendored from
4//! [`blake2b_simd`](https://github.com/oconnor663/blake2_simd) (MIT license),
5//! with modifications for EIP-152 variable round counts.
6
7use crate::{
8    crypto, eth_precompile_fn, EthPrecompileOutput, EthPrecompileResult, Precompile,
9    PrecompileHalt, PrecompileId,
10};
11
12#[cfg(all(
13    any(target_arch = "x86", target_arch = "x86_64"),
14    any(target_feature = "avx2", feature = "std")
15))]
16mod avx2;
17mod portable;
18
19type Word = u64;
20
21const F_ROUND: u64 = 1;
22const INPUT_LENGTH: usize = 213;
23
24const IV: [Word; 8] = [
25    0x6A09E667F3BCC908,
26    0xBB67AE8584CAA73B,
27    0x3C6EF372FE94F82B,
28    0xA54FF53A5F1D36F1,
29    0x510E527FADE682D1,
30    0x9B05688C2B3E6C1F,
31    0x1F83D9ABFB41BD6B,
32    0x5BE0CD19137E2179,
33];
34
35// SIGMA has spec period 10 (RFC 7693 §2.7). BLAKE2b runs 12 rounds by reusing
36// SIGMA[0]/SIGMA[1] for rounds 10/11; for EIP-152's variable round count we
37// must index with `r % 10`, not `r % 12`.
38const SIGMA: [[u8; 16]; 10] = [
39    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
40    [14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
41    [11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
42    [7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
43    [9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
44    [2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
45    [12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
46    [13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
47    [6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
48    [10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
49];
50
51/// BLAKE2b compression function F (EIP-152).
52///
53/// Dispatches to the best available implementation (AVX2 or portable).
54// On targets with no SIMD path the cfgs below collapse to the single `portable::compress` call,
55// which is `const`, so clippy suggests making this `const` too. It cannot be: on x86 this performs
56// runtime AVX2 feature detection and calls an `unsafe` intrinsic implementation.
57#[allow(clippy::missing_const_for_fn)]
58pub fn compress(rounds: u32, h: &mut [Word; 8], m: &[Word; 16], t: &[Word; 2], f: bool) {
59    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
60    {
61        #[cfg(target_feature = "avx2")]
62        {
63            unsafe { avx2::compress(rounds, h, m, t, f) };
64            return;
65        }
66        #[cfg(all(not(target_feature = "avx2"), feature = "std"))]
67        {
68            if std::is_x86_feature_detected!("avx2") {
69                unsafe { avx2::compress(rounds, h, m, t, f) };
70                return;
71            }
72        }
73    }
74    portable::compress(rounds, h, m, t, f);
75}
76
77/// The portable (non-SIMD) compression function, reachable directly.
78///
79/// Not public API -- use [`compress`], which always selects the fastest implementation for the
80/// target. This exists so benchmarks can measure the portable path on any host: [`compress`]
81/// detects AVX2 at runtime, so on an x86_64 CI runner a benchmark going through it measures the
82/// AVX2 path only, and the portable code that `no_std`, zkVM and non-x86 builds actually run is
83/// never timed.
84#[doc(hidden)]
85#[inline]
86pub const fn compress_portable(
87    rounds: u32,
88    h: &mut [Word; 8],
89    m: &[Word; 16],
90    t: &[Word; 2],
91    f: bool,
92) {
93    portable::compress(rounds, h, m, t, f);
94}
95
96eth_precompile_fn!(blake2_precompile, run);
97
98/// Blake2 precompile
99pub const FUN: Precompile = Precompile::new(
100    PrecompileId::Blake2F,
101    crate::u64_to_address(9),
102    blake2_precompile,
103);
104
105/// reference: <https://eips.ethereum.org/EIPS/eip-152>
106/// input format:
107/// [4 bytes for rounds][64 bytes for h][128 bytes for m][8 bytes for t_0][8 bytes for t_1][1 byte for f]
108pub fn run(input: &[u8], gas_limit: u64) -> EthPrecompileResult {
109    if input.len() != INPUT_LENGTH {
110        return Err(PrecompileHalt::Blake2WrongLength);
111    }
112
113    // Parse number of rounds (4 bytes)
114    let rounds = u32::from_be_bytes(input[..4].try_into().unwrap());
115    let gas_used = rounds as u64 * F_ROUND;
116    if gas_used > gas_limit {
117        return Err(PrecompileHalt::OutOfGas);
118    }
119
120    // Parse final block flag
121    let f = match input[212] {
122        0 => false,
123        1 => true,
124        _ => return Err(PrecompileHalt::Blake2WrongFinalIndicatorFlag),
125    };
126
127    // Parse state vector h (8 × u64)
128    let mut h = [0u64; 8];
129    input[4..68]
130        .as_chunks::<8>()
131        .0
132        .iter()
133        .enumerate()
134        .for_each(|(i, chunk)| {
135            h[i] = u64::from_le_bytes(*chunk);
136        });
137
138    // Parse message block m (16 × u64)
139    let mut m = [0u64; 16];
140    input[68..196]
141        .as_chunks::<8>()
142        .0
143        .iter()
144        .enumerate()
145        .for_each(|(i, chunk)| {
146            m[i] = u64::from_le_bytes(*chunk);
147        });
148
149    // Parse offset counters
150    let t_0 = u64::from_le_bytes(input[196..204].try_into().unwrap());
151    let t_1 = u64::from_le_bytes(input[204..212].try_into().unwrap());
152
153    crypto().blake2_compress(rounds, &mut h, &m, &[t_0, t_1], f);
154
155    let mut out = [0u8; 64];
156    for (i, h) in (0..64).step_by(8).zip(h.iter()) {
157        out[i..i + 8].copy_from_slice(&h.to_le_bytes());
158    }
159
160    Ok(EthPrecompileOutput::new(gas_used, out.into()))
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    /// Reference implementation: the compression function written with a runtime round index,
168    /// as it stood before the rounds were unrolled with a constant schedule. Deliberately kept
169    /// naive so that it is easy to check against RFC 7693 §3.2 by eye.
170    fn reference_compress(
171        rounds: u32,
172        words: &mut [Word; 8],
173        m: &[Word; 16],
174        t: &[Word; 2],
175        f: bool,
176    ) {
177        fn g(v: &mut [Word; 16], a: usize, b: usize, c: usize, d: usize, x: Word, y: Word) {
178            v[a] = v[a].wrapping_add(v[b]).wrapping_add(x);
179            v[d] = (v[d] ^ v[a]).rotate_right(32);
180            v[c] = v[c].wrapping_add(v[d]);
181            v[b] = (v[b] ^ v[c]).rotate_right(24);
182            v[a] = v[a].wrapping_add(v[b]).wrapping_add(y);
183            v[d] = (v[d] ^ v[a]).rotate_right(16);
184            v[c] = v[c].wrapping_add(v[d]);
185            v[b] = (v[b] ^ v[c]).rotate_right(63);
186        }
187
188        let mut v = [
189            words[0],
190            words[1],
191            words[2],
192            words[3],
193            words[4],
194            words[5],
195            words[6],
196            words[7],
197            IV[0],
198            IV[1],
199            IV[2],
200            IV[3],
201            IV[4] ^ t[0],
202            IV[5] ^ t[1],
203            IV[6] ^ if f { !0 } else { 0 },
204            IV[7],
205        ];
206
207        for r in 0..rounds as usize {
208            let s = SIGMA[r % 10];
209            g(&mut v, 0, 4, 8, 12, m[s[0] as usize], m[s[1] as usize]);
210            g(&mut v, 1, 5, 9, 13, m[s[2] as usize], m[s[3] as usize]);
211            g(&mut v, 2, 6, 10, 14, m[s[4] as usize], m[s[5] as usize]);
212            g(&mut v, 3, 7, 11, 15, m[s[6] as usize], m[s[7] as usize]);
213            g(&mut v, 0, 5, 10, 15, m[s[8] as usize], m[s[9] as usize]);
214            g(&mut v, 1, 6, 11, 12, m[s[10] as usize], m[s[11] as usize]);
215            g(&mut v, 2, 7, 8, 13, m[s[12] as usize], m[s[13] as usize]);
216            g(&mut v, 3, 4, 9, 14, m[s[14] as usize], m[s[15] as usize]);
217        }
218
219        for i in 0..8 {
220            words[i] ^= v[i] ^ v[i + 8];
221        }
222    }
223
224    /// splitmix64, so the inputs are varied but the failures are reproducible.
225    struct Rng(u64);
226
227    impl Rng {
228        fn next(&mut self) -> u64 {
229            self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
230            let mut z = self.0;
231            z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
232            z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
233            z ^ (z >> 31)
234        }
235    }
236
237    /// The unrolled portable implementation must agree with the runtime-index reference for
238    /// every round count, not just multiples of ten. Round counts 0..=40 cover an empty run, a
239    /// partial first tile, the wraparound at ten, and a full second tile; the larger counts
240    /// check that nothing drifts after many tiles.
241    ///
242    /// Note this calls `portable::compress` directly rather than the `compress` dispatcher, so
243    /// the portable path is exercised on every target, including those that would otherwise
244    /// dispatch to AVX2.
245    #[test]
246    fn portable_matches_runtime_index_reference() {
247        let mut rng = Rng(0x0DDB_1A5E_5BAD_5EED);
248
249        for rounds in (0u32..=40).chain([100, 101, 109, 110, 111, 1000, 4096]) {
250            for _ in 0..64 {
251                let mut h = [0u64; 8];
252                for w in h.iter_mut() {
253                    *w = rng.next();
254                }
255                let mut m = [0u64; 16];
256                for w in m.iter_mut() {
257                    *w = rng.next();
258                }
259                let t = [rng.next(), rng.next()];
260                let f = rng.next() & 1 == 0;
261
262                let mut got = h;
263                let mut want = h;
264                portable::compress(rounds, &mut got, &m, &t, f);
265                reference_compress(rounds, &mut want, &m, &t, f);
266
267                assert_eq!(
268                    got, want,
269                    "mismatch at rounds={rounds} f={f} h={h:?} m={m:?} t={t:?}"
270                );
271            }
272        }
273    }
274
275    /// EIP-152 test vector 4: an oracle independent of both implementations above. Twelve
276    /// rounds over "abc", the standard BLAKE2b parameters.
277    #[test]
278    fn eip152_vector_4() {
279        let h_in: [u64; 8] = [
280            0x6a09_e667_f2bd_c948,
281            0xbb67_ae85_84ca_a73b,
282            0x3c6e_f372_fe94_f82b,
283            0xa54f_f53a_5f1d_36f1,
284            0x510e_527f_ade6_82d1,
285            0x9b05_688c_2b3e_6c1f,
286            0x1f83_d9ab_fb41_bd6b,
287            0x5be0_cd19_137e_2179,
288        ];
289        let mut m = [0u64; 16];
290        m[0] = 0x0000_0000_0063_6261; // "abc"
291        let t = [3u64, 0u64];
292
293        let expected: [u64; 8] = [
294            0x0d4d_1c98_3fa5_80ba,
295            0xe9f6_129f_b697_276a,
296            0xb7c4_5a68_142f_214c,
297            0xd1a2_ffdb_6fbb_124b,
298            0x2d79_ab2a_39c5_877d,
299            0x95cc_3345_ded5_52c2,
300            0x5a92_f1db_a88a_d318,
301            0x2399_00d4_ed86_23b9,
302        ];
303
304        let mut h = h_in;
305        portable::compress(12, &mut h, &m, &t, true);
306        assert_eq!(h, expected, "portable");
307
308        // And through the dispatcher, so whichever implementation this target selects is
309        // checked against the same vector.
310        let mut h = h_in;
311        compress(12, &mut h, &m, &t, true);
312        assert_eq!(h, expected, "dispatched");
313    }
314}