Skip to content

Commit

Permalink
Sha3FIPS standard precompiles and ECDSA public key recovery (#304)
Browse files Browse the repository at this point in the history
* Sha3 and ECDSA precompiles

* Tests for sha3fips

* Updates to spec and adds tests

* Spacing and formatting

* Fmt

* Comment out test

* Updates

* Updates

* Update ECRecoverTests.sol

* Remove merge conflict

* Remove unnecessary yarn file

* Uncomment tests

* Fix tests

* Reset simple-specs.json change

* Remove unused frontier-spec.json file

Co-authored-by: Wei Tang <accounts@that.world>
Co-authored-by: Wei Tang <wei@that.world>
  • Loading branch information
3 people authored Mar 16, 2021
1 parent 4914624 commit 20964b1
Show file tree
Hide file tree
Showing 12 changed files with 2,850 additions and 1,407 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/rust.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,4 @@ jobs:
- name: Install functional tests typescript
run: cd ts-tests && npm install
- name: Run functional tests
run: cd ts-tests && npm run test
run: cd ts-tests && npm run build && npm run test
14 changes: 14 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ members = [
"frame/dynamic-fee",
"frame/ethereum",
"frame/evm",
"frame/evm/precompile/sha3fips",
"frame/evm/precompile/simple",
"frame/evm/precompile/modexp",
"frame/evm/precompile/ed25519",
Expand Down
25 changes: 25 additions & 0 deletions frame/evm/precompile/sha3fips/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
[package]
name = "pallet-evm-precompile-sha3fips"
version = "3.0.0"
authors = ["Parity Technologies <admin@parity.io>", "Drew Stone <drew@commonwealth.im>"]
edition = "2018"
license = "Apache-2.0"
homepage = "https://substrate.dev"
repository = "https://github.com/paritytech/substrate/"
description = "SHA3 FIPS202 precompile for EVM pallet."

[dependencies]
sp-core = { version = "3.0.0", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "frontier" }
sp-io = { version = "3.0.0", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "frontier" }
fp-evm = { version = "0.8.0", default-features = false, path = "../../../../primitives/evm" }
evm = { version = "0.24.0", default-features = false, features = ["with-codec"] }
tiny-keccak = { version = "2.0", features = ["fips202"] }

[features]
default = ["std"]
std = [
"sp-core/std",
"sp-io/std",
"fp-evm/std",
"evm/std",
]
153 changes: 153 additions & 0 deletions frame/evm/precompile/sha3fips/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// SPDX-License-Identifier: Apache-2.0
// This file is part of Frontier.
//
// Copyright (c) 2020 Parity Technologies (UK) Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use tiny_keccak::Hasher;
use alloc::vec::Vec;

use fp_evm::LinearCostPrecompile;
use evm::{ExitSucceed, ExitError};

pub struct Sha3FIPS256;

impl LinearCostPrecompile for Sha3FIPS256 {
const BASE: u64 = 60;
const WORD: u64 = 12;

fn execute(
input: &[u8],
_: u64,
) -> core::result::Result<(ExitSucceed, Vec<u8>), ExitError> {
let mut output = [0; 32];
let mut sha3 = tiny_keccak::Sha3::v256();
sha3.update(input);
sha3.finalize(&mut output);
Ok((ExitSucceed::Returned, output.to_vec()))
}
}

pub struct Sha3FIPS512;

impl LinearCostPrecompile for Sha3FIPS512 {
const BASE: u64 = 60;
const WORD: u64 = 12;

fn execute(
input: &[u8],
_: u64,
) -> core::result::Result<(ExitSucceed, Vec<u8>), ExitError> {
let mut output = [0; 64];
let mut sha3 = tiny_keccak::Sha3::v512();
sha3.update(input);
sha3.finalize(&mut output);
Ok((ExitSucceed::Returned, output.to_vec()))
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn test_empty_input() -> std::result::Result<(), ExitError> {
let input: [u8; 0] = [];
let expected = b"\
\xa7\xff\xc6\xf8\xbf\x1e\xd7\x66\x51\xc1\x47\x56\xa0\x61\xd6\x62\
\xf5\x80\xff\x4d\xe4\x3b\x49\xfa\x82\xd8\x0a\x4b\x80\xf8\x43\x4a\
";

let cost: u64 = 1;

match Sha3FIPS256::execute(&input, cost) {
Ok((_, out)) => {
assert_eq!(out, expected);
Ok(())
},
Err(e) => {
panic!("Test not expected to fail: {:?}", e);
}
}
}

#[test]
fn hello_sha3_256() -> std::result::Result<(), ExitError>{
let input = b"hello";
let expected = b"\
\x33\x38\xbe\x69\x4f\x50\xc5\xf3\x38\x81\x49\x86\xcd\xf0\x68\x64\
\x53\xa8\x88\xb8\x4f\x42\x4d\x79\x2a\xf4\xb9\x20\x23\x98\xf3\x92\
";

let cost: u64 = 1;

match Sha3FIPS256::execute(input, cost) {
Ok((_, out)) => {
assert_eq!(out, expected);
Ok(())
},
Err(e) => {
panic!("Test not expected to fail: {:?}", e);
}
}
}

#[test]
fn long_string_sha3_256() -> std::result::Result<(), ExitError>{
let input = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
let expected = b"\
\xbd\xe3\xf2\x69\x17\x5e\x1d\xcd\xa1\x38\x48\x27\x8a\xa6\x04\x6b\
\xd6\x43\xce\xa8\x5b\x84\xc8\xb8\xbb\x80\x95\x2e\x70\xb6\xea\xe0\
";

let cost: u64 = 1;

match Sha3FIPS256::execute(input, cost) {
Ok((_, out)) => {
assert_eq!(out, expected);
Ok(())
},
Err(e) => {
panic!("Test not expected to fail: {:?}", e);
}
}
}

#[test]
fn long_string_sha3_512() -> std::result::Result<(), ExitError>{
let input = b"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
let expected = b"\
\xf3\x2a\x94\x23\x55\x13\x51\xdf\x0a\x07\xc0\xb8\xc2\x0e\xb9\x72\
\x36\x7c\x39\x8d\x61\x06\x60\x38\xe1\x69\x86\x44\x8e\xbf\xbc\x3d\
\x15\xed\xe0\xed\x36\x93\xe3\x90\x5e\x9a\x8c\x60\x1d\x9d\x00\x2a\
\x06\x85\x3b\x97\x97\xef\x9a\xb1\x0c\xbd\xe1\x00\x9c\x7d\x0f\x09\
";

let cost: u64 = 1;

match Sha3FIPS512::execute(input, cost) {
Ok((_, out)) => {
assert_eq!(out, expected);
Ok(())
},
Err(e) => {
panic!("Test not expected to fail: {:?}", e);
}
}
}
}
29 changes: 29 additions & 0 deletions frame/evm/precompile/simple/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,32 @@ impl LinearCostPrecompile for Sha256 {
Ok((ExitSucceed::Returned, ret.to_vec()))
}
}

/// The ecrecover precompile.
pub struct ECRecoverPublicKey;

impl LinearCostPrecompile for ECRecoverPublicKey {
const BASE: u64 = 3000;
const WORD: u64 = 0;

fn execute(
i: &[u8],
_: u64,
) -> core::result::Result<(ExitSucceed, Vec<u8>), ExitError> {
let mut input = [0u8; 128];
input[..min(i.len(), 128)].copy_from_slice(&i[..min(i.len(), 128)]);

let mut msg = [0u8; 32];
let mut sig = [0u8; 65];

msg[0..32].copy_from_slice(&input[0..32]);
sig[0..32].copy_from_slice(&input[64..96]);
sig[32..64].copy_from_slice(&input[96..128]);
sig[64] = input[63];

let pubkey = sp_io::crypto::secp256k1_ecdsa_recover(&sig, &msg)
.map_err(|_| ExitError::Other("Public key recover failed".into()))?;

Ok((ExitSucceed::Returned, pubkey.to_vec()))
}
}
2 changes: 2 additions & 0 deletions template/runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ frame-system-rpc-runtime-api = { version = "3.0.0-dev", default-features = false
pallet-ethereum = { version = "0.1.0", default-features = false, path = "../../frame/ethereum" }
pallet-evm = { version = "3.0.0-dev", default-features = false, path = "../../frame/evm" }
pallet-evm-precompile-simple = { version = "3.0.0-dev", default-features = false, path = "../../frame/evm/precompile/simple" }
pallet-evm-precompile-sha3fips = { version = "3.0.0-dev", default-features = false, path = "../../frame/evm/precompile/sha3fips" }
pallet-aura = { version = "3.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "frontier" }
pallet-balances = { version = "3.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "frontier" }
pallet-grandpa = { version = "3.0.0-dev", default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "frontier" }
Expand Down Expand Up @@ -66,6 +67,7 @@ std = [
"pallet-ethereum/std",
"pallet-evm/std",
"pallet-evm-precompile-simple/std",
"pallet-evm-precompile-sha3fips/std",
"pallet-aura/std",
"pallet-balances/std",
"pallet-grandpa/std",
Expand Down
3 changes: 3 additions & 0 deletions template/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@ impl pallet_evm::Config for Runtime {
pallet_evm_precompile_simple::Sha256,
pallet_evm_precompile_simple::Ripemd160,
pallet_evm_precompile_simple::Identity,
pallet_evm_precompile_simple::ECRecoverPublicKey,
pallet_evm_precompile_sha3fips::Sha3FIPS256,
pallet_evm_precompile_sha3fips::Sha3FIPS512,
);
type ChainId = ChainId;
type OnChargeTransaction = ();
Expand Down
9 changes: 9 additions & 0 deletions ts-tests/contracts/ECRecoverTests.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pragma solidity 0.8.2;

contract ECRecoverTests {
function ecrecover(bytes memory input) public returns(bytes memory) {
address ecrecoverAddress = address(0x0000000000000000000000000000000000000001);
(bool success, bytes memory returnData) = ecrecoverAddress.call(input);
return returnData;
}
}
Loading

0 comments on commit 20964b1

Please sign in to comment.