Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

members = [
"blake2",
"blake2f",
"bls12pairing",
"ecadd",
"ecmul",
Expand Down
20 changes: 20 additions & 0 deletions blake2f/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "ewasm-precompile-blake2f"
version = "0.2.0"
authors = ["Grant Wuerker <gwuerker@gmail.com>"]
license = "Apache-2.0"
repository = "https://github.com/ewasm/ewasm-precompiles"
description = "Ethereum Blake2 compression function precompile in Rust"
publish = false
edition = "2018"

[dependencies]
byteorder = "1.3.4"
ewasm_api = "0.9"
arr_macro = "0.1.3"

[dev-dependencies]
hex = "0.3.1"

[lib]
crate-type = ["cdylib"]
25 changes: 25 additions & 0 deletions blake2f/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
This program is copyright 2020 Parity Technologies Limited and its licensors.

GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007

Some portions of the program (“the Software”) are Copyright (c) 2018 Jack O'Connor
and the following relates solely to such portions:

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
83 changes: 83 additions & 0 deletions blake2f/src/f.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/// The following code has been copied from the OpenEthereum project, which is distributed under
/// the terms of the GNU General Public License. A copy of its license has been included in this
/// crate.
///
/// https://github.com/openethereum/openethereum/tree/master/util/EIP-152

/// The precomputed values for BLAKE2b [from the spec](https://tools.ietf.org/html/rfc7693#section-2.7)
/// There are 10 16-byte arrays - one for each round
/// the entries are calculated from the sigma constants.
const SIGMA: [[usize; 16]; 10] = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
[7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8],
[9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13],
[2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9],
[12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11],
[13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10],
[6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5],
[10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0],
];

/// IV is the initialization vector for BLAKE2b. See https://tools.ietf.org/html/rfc7693#section-2.6
/// for details.
const IV: [u64; 8] = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
0xa54ff53a5f1d36f1,
0x510e527fade682d1,
0x9b05688c2b3e6c1f,
0x1f83d9abfb41bd6b,
0x5be0cd19137e2179,
];

/// The G mixing function. See https://tools.ietf.org/html/rfc7693#section-3.1
#[inline(always)]
fn g(v: &mut [u64], a: usize, b: usize, c: usize, d: usize, x: u64, y: u64) {
v[a] = v[a].wrapping_add(v[b]).wrapping_add(x);
v[d] = (v[d] ^ v[a]).rotate_right(32);
v[c] = v[c].wrapping_add(v[d]);
v[b] = (v[b] ^ v[c]).rotate_right(24);

v[a] = v[a].wrapping_add(v[b]).wrapping_add(y);
v[d] = (v[d] ^ v[a]).rotate_right(16);
v[c] = v[c].wrapping_add(v[d]);
v[b] = (v[b] ^ v[c]).rotate_right(63);
}

/// The Blake2b compression function F. See https://tools.ietf.org/html/rfc7693#section-3.2
/// Takes as an argument the state vector `h`, message block vector `m`, offset counter `t`, final
/// block indicator flag `f`, and number of rounds `rounds`. The state vector provided as the first
/// parameter is modified by the function.
pub fn compress(rounds: usize, h: &mut [u64; 8], m: [u64; 16], t: [u64; 2], f: bool) {
let mut v = [0u64; 16];
v[..8].copy_from_slice(h); // First half from state.
v[8..].copy_from_slice(&IV); // Second half from IV.

v[12] ^= t[0];
v[13] ^= t[1];

if f {
v[14] = !v[14]; // Invert all bits if the last-block-flag is set.
}

for i in 0..rounds {
// Message word selection permutation for this round.
let s = &SIGMA[i % 10];
g(&mut v, 0, 4, 8, 12, m[s[0]], m[s[1]]);
g(&mut v, 1, 5, 9, 13, m[s[2]], m[s[3]]);
g(&mut v, 2, 6, 10, 14, m[s[4]], m[s[5]]);
g(&mut v, 3, 7, 11, 15, m[s[6]], m[s[7]]);

g(&mut v, 0, 5, 10, 15, m[s[8]], m[s[9]]);
g(&mut v, 1, 6, 11, 12, m[s[10]], m[s[11]]);
g(&mut v, 2, 7, 8, 13, m[s[12]], m[s[13]]);
g(&mut v, 3, 4, 9, 14, m[s[14]], m[s[15]]);
}

for i in 0..8 {
h[i] ^= v[i] ^ v[i + 8];
}
}
190 changes: 190 additions & 0 deletions blake2f/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
//! Blake2f precompile as described in EIP-152

extern crate ewasm_api;

mod f;

use arr_macro::arr;
use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;

#[cfg(not(test))]
#[no_mangle]
pub extern "C" fn main() {
match blake2_f(ewasm_api::calldata_acquire()) {
Ok((gas_used, data)) => {
ewasm_api::consume_gas(gas_used);
ewasm_api::finish_data(data.as_slice())
}
Err(err) => ewasm_api::revert_data(err.as_bytes()),
}
}

/// The Blake2F precompile written as a Result returning function.
pub fn blake2_f(data: Vec<u8>) -> Result<(u64, Vec<u8>), &'static str> {
if data.len() == 213 {
let (rounds, mut h, m, t, f) = read_data(data)?;
f::compress(rounds as usize, &mut h, m, t, f);

return Ok((rounds as u64, write_data(h)));
}

Err("input length for BLAKE2 F precompile should be exactly 213 bytes")
}

fn read_data(data: Vec<u8>) -> Result<(u32, [u64; 8], [u64; 16], [u64; 2], bool), &'static str> {
let mut reader = Cursor::new(data);

let rounds = reader
.read_u32::<BigEndian>()
.expect("Unable to read data.");
let h = arr![reader.read_u64::<LittleEndian>().expect("Unable to read data."); 8];
let m = arr![reader.read_u64::<LittleEndian>().expect("Unable to read data."); 16];
let t = arr![reader.read_u64::<LittleEndian>().expect("Unable to read data."); 2];
let f = match reader.read_u8().expect("Unable to read data.") {
0 => false,
1 => true,
_ => return Err("incorrect final block indicator flag"),
};

Ok((rounds, h, m, t, f))
}

fn write_data(h: [u64; 8]) -> Vec<u8> {
let mut data = vec![];

for i in 0..8 {
data.write_u64::<LittleEndian>(h[i])
.expect("Unable to write data.")
}

data
}

/// See test cases at https://eips.ethereum.org/EIPS/eip-152.
///
/// You will most likely need to override the default target like so:
/// Example: `cargo test --target x86_64-unknown-linux-gnu --release`
#[cfg(test)]
mod tests {
extern crate hex;

use crate::blake2_f;
use std::time::Instant;

const INPUTS: [&str; 9] = [
"",
"00000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
"000000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
"0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000002",
"0000000048c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
"0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
"0000000c48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000000",
"0000000148c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
"ffffffff48c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001",
];

const OUTPUTS: [&str; 9] = [
"",
"",
"",
"",
"08c9bcf367e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d282e6ad7f520e511f6c3e2b8c68059b9442be0454267ce079217e1319cde05b",
"ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923",
"75ab69d3190a562c51aef8d88f1c2775876944407270c42c9844252c26d2875298743e7f6d5ea2f2d3e8d226039cd31b4e426ac4f2d3d666a610c2116fde4735",
"b63a380cb2897d521994a85234ee2c181b5f844d2c624c002677e9703449d2fba551b3a8333bcdf5f2f7e08993d53923de3d64fcc68c034e717b9293fed7a421",
"fc59093aafa9ab43daae0e914c57635c5402d8e3d2130eb9b3cc181de7f0ecf9b22bf99a7815ce16419e200e01846e6b5df8cc7703041bbceb571de6631d2615",
];

/// 1200 rounds
const BENCH_INPUT: &str = "000004B048c9bdf267e6096a3ba7ca8485ae67bb2bf894fe72f36e3cf1361d5f3af54fa5d182e6ad7f520e511f6c3e2b8c68059b6bbd41fbabd9831f79217e1319cde05b61626300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000300000000000000000000000000000001";

#[test]
fn case0() {
assert_eq!(
blake2_f(hex::decode(INPUTS[0]).unwrap()),
Err("input length for BLAKE2 F precompile should be exactly 213 bytes"),
)
}

#[test]
fn case1() {
assert_eq!(
blake2_f(hex::decode(INPUTS[1]).unwrap()),
Err("input length for BLAKE2 F precompile should be exactly 213 bytes"),
)
}

#[test]
fn case2() {
assert_eq!(
blake2_f(hex::decode(INPUTS[2]).unwrap()),
Err("input length for BLAKE2 F precompile should be exactly 213 bytes"),
)
}

#[test]
fn case3() {
assert_eq!(
blake2_f(hex::decode(INPUTS[3]).unwrap()),
Err("incorrect final block indicator flag"),
)
}

#[test]
fn case4() {
assert_eq!(
blake2_f(hex::decode(INPUTS[4]).unwrap()),
Ok((0, hex::decode(OUTPUTS[4]).unwrap())),
)
}

#[test]
fn case5() {
assert_eq!(
blake2_f(hex::decode(INPUTS[5]).unwrap()),
Ok((12, hex::decode(OUTPUTS[5]).unwrap())),
)
}

#[test]
fn case6() {
assert_eq!(
blake2_f(hex::decode(INPUTS[6]).unwrap()),
Ok((12, hex::decode(OUTPUTS[6]).unwrap())),
)
}

#[test]
fn case7() {
assert_eq!(
blake2_f(hex::decode(INPUTS[7]).unwrap()),
Ok((1, hex::decode(OUTPUTS[7]).unwrap())),
)
}

// This test takes excessively long.
//
// #[test]
// fn case8() {
// assert_eq!(
// blake2_f(hex::decode(INPUTS[8]).unwrap()),
// Ok((4294967295, hex::decode(OUTPUTS[8]).unwrap())),
// );
// }

/// run with `-- --nocapture`
#[test]
fn benchmark() {
let n = 1000;
let mut sum = 0;

for _ in 0..n {
let now = Instant::now();
blake2_f(hex::decode(BENCH_INPUT).unwrap()).expect("Couldn't compress BENCH_INPUT.");
sum += now.elapsed().as_nanos();
}

println!("Average elapsed time for 1200 rounds: {}ns", sum / n)
}
}
15 changes: 15 additions & 0 deletions chisel.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,21 @@ blake2:
repack:
preset: "ewasm"

blake2f:
file: "target/wasm32-unknown-unknown/release/ewasm_precompile_blake2f.wasm"
remapimports:
preset: "ewasm"
trimexports:
preset: "ewasm"
verifyimports:
preset: "ewasm"
verifyexports:
preset: "ewasm"
snip:
preset: "ewasm"
repack:
preset: "ewasm"

bls12pairing:
file: "target/wasm32-unknown-unknown/release/ewasm_precompile_bls12pairing.wasm"
remapimports:
Expand Down