ovr_evm_test_vector_support/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2// This file is part of Frontier.
3//
4// Copyright (c) 2020 Parity Technologies (UK) Ltd.
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 evm::{Context, ExitSucceed};
19use fp_evm::Precompile;
20
21use serde::Deserialize;
22
23#[allow(non_snake_case)]
24#[derive(Deserialize, Debug)]
25struct EthConsensusTest {
26	Input: String,
27	Expected: String,
28	Name: String,
29	Gas: Option<u64>,
30}
31
32/// Tests a precompile against the ethereum consensus tests defined in the given file at filepath.
33/// The file is expected to be in JSON format and contain an array of test vectors, where each
34/// vector can be deserialized into an "EthConsensusTest".
35pub fn test_precompile_test_vectors<P: Precompile>(filepath: &str) -> Result<(), String> {
36	use std::fs;
37
38	let data = fs::read_to_string(&filepath).expect("Failed to read blake2F.json");
39
40	let tests: Vec<EthConsensusTest> = serde_json::from_str(&data).expect("expected json array");
41
42	for test in tests {
43		let input: Vec<u8> = hex::decode(test.Input).expect("Could not hex-decode test input data");
44
45		let cost: u64 = 10000000;
46
47		let context: Context = Context {
48			address: Default::default(),
49			caller: Default::default(),
50			apparent_value: From::from(0),
51		};
52
53		match P::execute(&input, Some(cost), &context, false) {
54			Ok(result) => {
55				let as_hex: String = hex::encode(result.output);
56				assert_eq!(
57					result.exit_status,
58					ExitSucceed::Returned,
59					"test '{}' returned {:?} (expected 'Returned')",
60					test.Name,
61					result.exit_status
62				);
63				assert_eq!(
64					as_hex, test.Expected,
65					"test '{}' failed (different output)",
66					test.Name
67				);
68				if let Some(expected_gas) = test.Gas {
69					assert_eq!(
70						result.cost, expected_gas,
71						"test '{}' failed (different gas cost)",
72						test.Name
73					);
74				}
75			}
76			Err(err) => {
77				return Err(format!("Test '{}' returned error: {:?}", test.Name, err));
78			}
79		}
80	}
81
82	Ok(())
83}