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).
54pub fn compress(rounds: u32, h: &mut [Word; 8], m: &[Word; 16], t: &[Word; 2], f: bool) {
55    #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
56    {
57        #[cfg(target_feature = "avx2")]
58        {
59            unsafe { avx2::compress(rounds, h, m, t, f) };
60            return;
61        }
62        #[cfg(all(not(target_feature = "avx2"), feature = "std"))]
63        {
64            if std::is_x86_feature_detected!("avx2") {
65                unsafe { avx2::compress(rounds, h, m, t, f) };
66                return;
67            }
68        }
69    }
70    portable::compress(rounds, h, m, t, f);
71}
72
73eth_precompile_fn!(blake2_precompile, run);
74
75/// Blake2 precompile
76pub const FUN: Precompile = Precompile::new(
77    PrecompileId::Blake2F,
78    crate::u64_to_address(9),
79    blake2_precompile,
80);
81
82/// reference: <https://eips.ethereum.org/EIPS/eip-152>
83/// input format:
84/// [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]
85pub fn run(input: &[u8], gas_limit: u64) -> EthPrecompileResult {
86    if input.len() != INPUT_LENGTH {
87        return Err(PrecompileHalt::Blake2WrongLength);
88    }
89
90    // Parse number of rounds (4 bytes)
91    let rounds = u32::from_be_bytes(input[..4].try_into().unwrap());
92    let gas_used = rounds as u64 * F_ROUND;
93    if gas_used > gas_limit {
94        return Err(PrecompileHalt::OutOfGas);
95    }
96
97    // Parse final block flag
98    let f = match input[212] {
99        0 => false,
100        1 => true,
101        _ => return Err(PrecompileHalt::Blake2WrongFinalIndicatorFlag),
102    };
103
104    // Parse state vector h (8 × u64)
105    let mut h = [0u64; 8];
106    input[4..68]
107        .chunks_exact(8)
108        .enumerate()
109        .for_each(|(i, chunk)| {
110            h[i] = u64::from_le_bytes(chunk.try_into().unwrap());
111        });
112
113    // Parse message block m (16 × u64)
114    let mut m = [0u64; 16];
115    input[68..196]
116        .chunks_exact(8)
117        .enumerate()
118        .for_each(|(i, chunk)| {
119            m[i] = u64::from_le_bytes(chunk.try_into().unwrap());
120        });
121
122    // Parse offset counters
123    let t_0 = u64::from_le_bytes(input[196..204].try_into().unwrap());
124    let t_1 = u64::from_le_bytes(input[204..212].try_into().unwrap());
125
126    crypto().blake2_compress(rounds, &mut h, &m, &[t_0, t_1], f);
127
128    let mut out = [0u8; 64];
129    for (i, h) in (0..64).step_by(8).zip(h.iter()) {
130        out[i..i + 8].copy_from_slice(&h.to_le_bytes());
131    }
132
133    Ok(EthPrecompileOutput::new(gas_used, out.into()))
134}