From 25b35ebddd11e400d48c891bf5ea4b75851ea4cf Mon Sep 17 00:00:00 2001 From: Arkadiy Paronyan Date: Fri, 15 Sep 2017 21:07:54 +0200 Subject: [PATCH] Byzantium updates (#5855) * EIP-211 updates * benchmarks * blockhash instruction gas cost updated * More benches * EIP-684 * EIP-649 * EIP-658 * Updated some tests * Modexp fixes * STATICCALL fixes * Pairing fixes * More STATICALL fixes * Use paritytech/bn * Fixed REVERTing of contract creation * Fixed more tests * Fixed more tests * Blockchain tests * Enable previously broken tests * Transition test * Updated tests * Fixed modexp reading huge numbers * Enabled max_code_size test * Review fixes * Updated pairing pricing * missing commas (style) * Update test.rs * Small improvements * eip161abc --- ethcore/benches/evm.rs | 97 ++++++++ ethcore/evm/src/evm.rs | 3 +- ethcore/evm/src/interpreter/mod.rs | 42 +++- ethcore/light/src/on_demand/request.rs | 1 + ethcore/res/ethereum/byzantium_test.json | 60 +++++ ...lis_test.json => constantinople_test.json} | 22 +- ethcore/res/ethereum/foundation.json | 8 +- ethcore/res/ethereum/tests | 2 +- ethcore/res/ethereum/transition_test.json | 157 ++---------- ethcore/src/blockchain/blockchain.rs | 3 + ethcore/src/builtin.rs | 233 ++++++++++-------- ethcore/src/client/client.rs | 2 + ethcore/src/client/evm_test_client.rs | 29 ++- ethcore/src/client/test_client.rs | 1 + ethcore/src/engines/mod.rs | 4 +- ethcore/src/ethereum/ethash.rs | 29 ++- ethcore/src/ethereum/mod.rs | 7 +- ethcore/src/executive.rs | 65 +++-- ethcore/src/externalities.rs | 37 ++- ethcore/src/json_tests/chain.rs | 115 ++++----- ethcore/src/json_tests/executive.rs | 33 ++- ethcore/src/json_tests/homestead_chain.rs | 39 --- ethcore/src/json_tests/mod.rs | 1 - ethcore/src/json_tests/state.rs | 9 +- ethcore/src/json_tests/transaction.rs | 29 +-- ethcore/src/spec/spec.rs | 33 ++- ethcore/src/state/mod.rs | 22 +- ethcore/src/tests/evm.rs | 2 +- ethcore/src/tests/helpers.rs | 23 +- ethcore/src/trace/types/error.rs | 12 + ethcore/types/src/receipt.rs | 28 ++- ethcore/vm/src/error.rs | 6 + ethcore/vm/src/ext.rs | 17 +- ethcore/vm/src/schedule.rs | 9 +- ethcore/vm/src/tests.rs | 6 +- ethcore/wasm/src/runtime.rs | 16 +- evmbin/src/main.rs | 2 +- json/src/blockchain/blockchain.rs | 8 +- json/src/spec/builtin.rs | 12 + json/src/spec/ethash.rs | 18 ++ json/src/spec/params.rs | 3 + json/src/state/test.rs | 6 +- json/src/vm/log.rs | 54 ---- json/src/vm/mod.rs | 2 - json/src/vm/vm.rs | 11 +- rpc/src/v1/tests/eth.rs | 17 +- rpc/src/v1/tests/mod.rs | 35 +-- 47 files changed, 800 insertions(+), 570 deletions(-) create mode 100644 ethcore/benches/evm.rs create mode 100644 ethcore/res/ethereum/byzantium_test.json rename ethcore/res/ethereum/{metropolis_test.json => constantinople_test.json} (63%) delete mode 100644 ethcore/src/json_tests/homestead_chain.rs delete mode 100644 json/src/vm/log.rs diff --git a/ethcore/benches/evm.rs b/ethcore/benches/evm.rs new file mode 100644 index 000000000..384aa60a6 --- /dev/null +++ b/ethcore/benches/evm.rs @@ -0,0 +1,97 @@ +// Copyright 2015-2017 Parity Technologies (UK) Ltd. +// This file is part of Parity. + +// Parity is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity. If not, see . + +#![feature(test)] + +extern crate test; +extern crate ethcore_util as util; +extern crate rand; +extern crate bn; +extern crate crypto; +extern crate rustc_serialize; +extern crate ethkey; + +use self::test::{Bencher}; +use rand::{StdRng}; + + +#[bench] +fn bn_128_pairing(b: &mut Bencher) { + use bn::{pairing, G1, G2, Fr, Group}; + + let rng = &mut ::rand::thread_rng(); + + let sk0 = Fr::random(rng); + let sk1 = Fr::random(rng); + + let pk0 = G1::one() * sk0; + let pk1 = G2::one() * sk1; + + b.iter(|| { + let _ = pairing(pk0, pk1); + }); +} + +#[bench] +fn bn_128_mul(b: &mut Bencher) { + use bn::{AffineG1, G1, Fr, Group}; + + let mut rng = StdRng::new().unwrap(); + let p: G1 = G1::random(&mut rng); + let fr = Fr::random(&mut rng); + + b.iter(|| { + let _ = AffineG1::from_jacobian(p * fr); + }); +} + +#[bench] +fn sha256(b: &mut Bencher) { + use crypto::sha2::Sha256; + use crypto::digest::Digest; + + let mut input: [u8; 256] = [0; 256]; + let mut out = [0; 32]; + + b.iter(|| { + let mut sha = Sha256::new(); + sha.input(&input); + sha.result(&mut input[0..32]); + }); +} + +#[bench] +fn ecrecover(b: &mut Bencher) { + use rustc_serialize::hex::FromHex; + use ethkey::{Signature, recover as ec_recover}; + use util::H256; + let input = FromHex::from_hex("47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad000000000000000000000000000000000000000000000000000000000000001b650acf9d3f5f0a2c799776a1254355d5f4061762a237396a99a0e0e3fc2bcd6729514a0dacb2e623ac4abd157cb18163ff942280db4d5caad66ddf941ba12e03").unwrap(); + let hash = H256::from_slice(&input[0..32]); + let v = H256::from_slice(&input[32..64]); + let r = H256::from_slice(&input[64..96]); + let s = H256::from_slice(&input[96..128]); + + let bit = match v[31] { + 27 | 28 if &v.0[..31] == &[0; 31] => v[31] - 27, + _ => { return; }, + }; + + let s = Signature::from_rsv(&r, &s, bit); + b.iter(|| { + let _ = ec_recover(&s, &hash); + }); +} + diff --git a/ethcore/evm/src/evm.rs b/ethcore/evm/src/evm.rs index 9eedb3c51..9a887d040 100644 --- a/ethcore/evm/src/evm.rs +++ b/ethcore/evm/src/evm.rs @@ -17,7 +17,6 @@ //! Evm interface. use std::{ops, cmp, fmt}; - use bigint::prelude::{U128, U256, U512}; use vm::{Ext, Result, ReturnData, GasLeft, Error}; @@ -46,7 +45,7 @@ impl Finalize for Result { fn finalize(self, ext: E) -> Result { match self { Ok(GasLeft::Known(gas_left)) => Ok(FinalizationResult { gas_left: gas_left, apply_state: true, return_data: ReturnData::empty() }), - Ok(GasLeft::NeedsReturn {gas_left, data, apply_state}) => ext.ret(&gas_left, &data).map(|gas_left| FinalizationResult { + Ok(GasLeft::NeedsReturn {gas_left, data, apply_state}) => ext.ret(&gas_left, &data, apply_state).map(|gas_left| FinalizationResult { gas_left: gas_left, apply_state: apply_state, return_data: data, diff --git a/ethcore/evm/src/interpreter/mod.rs b/ethcore/evm/src/interpreter/mod.rs index a59a37db0..11959ee8e 100644 --- a/ethcore/evm/src/interpreter/mod.rs +++ b/ethcore/evm/src/interpreter/mod.rs @@ -328,6 +328,9 @@ impl Interpreter { let contract_code = self.mem.read_slice(init_off, init_size); let can_create = ext.balance(¶ms.address)? >= endowment && ext.depth() < ext.schedule().max_depth; + // clear return data buffer before creating new call frame. + self.return_data = ReturnData::empty(); + if !can_create { stack.push(U256::zero()); return Ok(InstructionResult::UnusedGas(create_gas)); @@ -339,10 +342,18 @@ impl Interpreter { stack.push(address_to_u256(address)); Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater."))) }, + ContractCreateResult::Reverted(gas_left, return_data) => { + stack.push(U256::zero()); + self.return_data = return_data; + Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater."))) + }, ContractCreateResult::Failed => { stack.push(U256::zero()); Ok(InstructionResult::Ok) - } + }, + ContractCreateResult::FailedInStaticCall => { + Err(vm::Error::MutableCallInStaticContext) + }, }; }, instructions::CALL | instructions::CALLCODE | instructions::DELEGATECALL | instructions::STATICCALL => { @@ -353,8 +364,10 @@ impl Interpreter { let code_address = stack.pop_back(); let code_address = u256_to_address(&code_address); - let value = if instruction == instructions::DELEGATECALL || instruction == instructions::STATICCALL { + let value = if instruction == instructions::DELEGATECALL { None + } else if instruction == instructions::STATICCALL { + Some(U256::zero()) } else { Some(stack.pop_back()) }; @@ -373,6 +386,9 @@ impl Interpreter { // Get sender & receive addresses, check if we have balance let (sender_address, receive_address, has_balance, call_type) = match instruction { instructions::CALL => { + if ext.is_static() && value.map_or(false, |v| !v.is_zero()) { + return Err(vm::Error::MutableCallInStaticContext); + } let has_balance = ext.balance(¶ms.address)? >= value.expect("value set for all but delegate call; qed"); (¶ms.address, &code_address, has_balance, CallType::Call) }, @@ -381,10 +397,13 @@ impl Interpreter { (¶ms.address, ¶ms.address, has_balance, CallType::CallCode) }, instructions::DELEGATECALL => (¶ms.sender, ¶ms.address, true, CallType::DelegateCall), - instructions::STATICCALL => (¶ms.sender, ¶ms.address, true, CallType::StaticCall), + instructions::STATICCALL => (¶ms.address, &code_address, true, CallType::StaticCall), _ => panic!(format!("Unexpected instruction {} in CALL branch.", instruction)) }; + // clear return data buffer before creating new call frame. + self.return_data = ReturnData::empty(); + let can_call = has_balance && ext.depth() < ext.schedule().max_depth; if !can_call { stack.push(U256::zero()); @@ -403,12 +422,17 @@ impl Interpreter { MessageCallResult::Success(gas_left, data) => { stack.push(U256::one()); self.return_data = data; - Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater then current one"))) + Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater than current one"))) + }, + MessageCallResult::Reverted(gas_left, data) => { + stack.push(U256::zero()); + self.return_data = data; + Ok(InstructionResult::UnusedGas(Cost::from_u256(gas_left).expect("Gas left cannot be greater than current one"))) }, MessageCallResult::Failed => { stack.push(U256::zero()); Ok(InstructionResult::Ok) - } + }, }; }, instructions::RETURN => { @@ -546,6 +570,14 @@ impl Interpreter { Self::copy_data_to_memory(&mut self.mem, stack, params.data.as_ref().map_or_else(|| &[] as &[u8], |d| &*d as &[u8])); }, instructions::RETURNDATACOPY => { + { + let source_offset = stack.peek(1); + let size = stack.peek(2); + let return_data_len = U256::from(self.return_data.len()); + if source_offset.overflow_add(*size).0 > return_data_len { + return Err(vm::Error::OutOfBounds); + } + } Self::copy_data_to_memory(&mut self.mem, stack, &*self.return_data); }, instructions::CODECOPY => { diff --git a/ethcore/light/src/on_demand/request.rs b/ethcore/light/src/on_demand/request.rs index 162e2bb3a..495d56bd9 100644 --- a/ethcore/light/src/on_demand/request.rs +++ b/ethcore/light/src/on_demand/request.rs @@ -974,6 +974,7 @@ mod tests { fn check_receipts() { let receipts = (0..5).map(|_| Receipt { state_root: Some(H256::random()), + status_code: None, gas_used: 21_000u64.into(), log_bloom: Default::default(), logs: Vec::new(), diff --git a/ethcore/res/ethereum/byzantium_test.json b/ethcore/res/ethereum/byzantium_test.json new file mode 100644 index 000000000..4d239c04e --- /dev/null +++ b/ethcore/res/ethereum/byzantium_test.json @@ -0,0 +1,60 @@ +{ + "name": "Byzantium (Test)", + "engine": { + "Ethash": { + "params": { + "minimumDifficulty": "0x020000", + "difficultyBoundDivisor": "0x0800", + "durationLimit": "0x0d", + "homesteadTransition": "0x0", + "eip150Transition": "0x0", + "eip160Transition": "0x0", + "eip161abcTransition": "0x0", + "eip161dTransition": "0x0", + "maxCodeSize": 24576, + "eip649Reward": "0x29A2241AF62C0000", + "eip100bTransition": "0x0", + "eip649Transition": "0x0" + } + } + }, + "params": { + "gasLimitBoundDivisor": "0x0400", + "blockReward": "0x4563918244F40000", + "registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b", + "accountStartNonce": "0x00", + "maximumExtraDataSize": "0x20", + "minGasLimit": "0x1388", + "networkID" : "0x1", + "eip98Transition": "0xffffffffffffffff", + "eip140Transition": "0x0", + "eip211Transition": "0x0", + "eip214Transition": "0x0", + "eip155Transition": "0x0", + "eip658Transition": "0x0" + }, + "genesis": { + "seal": { + "ethereum": { + "nonce": "0x0000000000000042", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000" + } + }, + "difficulty": "0x400000000", + "author": "0x0000000000000000000000000000000000000000", + "timestamp": "0x00", + "parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000", + "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", + "gasLimit": "0x1388" + }, + "accounts": { + "0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, + "0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, + "0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, + "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }, + "0000000000000000000000000000000000000005": { "builtin": { "name": "modexp", "activate_at": "0x00", "pricing": { "modexp": { "divisor": 20 } } } }, + "0000000000000000000000000000000000000006": { "builtin": { "name": "alt_bn128_add", "activate_at": "0x00", "pricing": { "linear": { "base": 500, "word": 0 } } } }, + "0000000000000000000000000000000000000007": { "builtin": { "name": "alt_bn128_mul", "activate_at": "0x00", "pricing": { "linear": { "base": 40000, "word": 0 } } } }, + "0000000000000000000000000000000000000008": { "builtin": { "name": "alt_bn128_pairing", "activate_at": "0x00", "pricing": { "alt_bn128_pairing": { "base": 100000, "pair": 80000 } } } } + } +} diff --git a/ethcore/res/ethereum/metropolis_test.json b/ethcore/res/ethereum/constantinople_test.json similarity index 63% rename from ethcore/res/ethereum/metropolis_test.json rename to ethcore/res/ethereum/constantinople_test.json index a452e5a80..d6df0dddb 100644 --- a/ethcore/res/ethereum/metropolis_test.json +++ b/ethcore/res/ethereum/constantinople_test.json @@ -1,18 +1,20 @@ { - "name": "Metropolis (Test)", + "name": "Byzantium (Test)", "engine": { "Ethash": { "params": { "minimumDifficulty": "0x020000", "difficultyBoundDivisor": "0x0800", "durationLimit": "0x0d", - "homesteadTransition": "0x0", "eip150Transition": "0x0", "eip160Transition": "0x0", "eip161abcTransition": "0x0", "eip161dTransition": "0x0", - "maxCodeSize": 24576 + "maxCodeSize": 24576, + "eip649Reward": "0x29A2241AF62C0000", + "eip100bTransition": "0x0", + "eip649Transition": "0x0" } } }, @@ -24,11 +26,13 @@ "maximumExtraDataSize": "0x20", "minGasLimit": "0x1388", "networkID" : "0x1", - "eip98Transition": "0x0", - "eip86Transition": "0x0", + "eip98Transition": "0xffffffffffffffff", "eip140Transition": "0x0", "eip210Transition": "0x0", - "eip155Transition": "0x0" + "eip211Transition": "0x0", + "eip214Transition": "0x0", + "eip155Transition": "0x0", + "eip658Transition": "0x0" }, "genesis": { "seal": { @@ -48,6 +52,10 @@ "0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, "0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, "0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, - "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } } + "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }, + "0000000000000000000000000000000000000005": { "builtin": { "name": "modexp", "activate_at": "0x00", "pricing": { "modexp": { "divisor": 100 } } } }, + "0000000000000000000000000000000000000006": { "builtin": { "name": "alt_bn128_add", "activate_at": "0x00", "pricing": { "linear": { "base": 500, "word": 0 } } } }, + "0000000000000000000000000000000000000007": { "builtin": { "name": "alt_bn128_mul", "activate_at": "0x00", "pricing": { "linear": { "base": 2000, "word": 0 } } } }, + "0000000000000000000000000000000000000008": { "builtin": { "name": "alt_bn128_pairing", "activate_at": "0x00", "pricing": { "alt_bn128_pairing": { "base": 100000, "pair": 80000 } } } } } } diff --git a/ethcore/res/ethereum/foundation.json b/ethcore/res/ethereum/foundation.json index b30453082..3e87d2e14 100644 --- a/ethcore/res/ethereum/foundation.json +++ b/ethcore/res/ethereum/foundation.json @@ -191,10 +191,10 @@ "0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, "0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, "0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }, - "0000000000000000000000000000000000000005": { "builtin": { "name": "modexp", "activate_at": "0x7fffffffffffff", "pricing": { "modexp": { "divisor": 20 } } } }, - "0000000000000000000000000000000000000006": { "builtin": { "name": "bn128_add", "activate_at": "0x7fffffffffffff", "pricing": { "linear": { "base": 999999, "word": 0 } } } }, - "0000000000000000000000000000000000000007": { "builtin": { "name": "bn128_mul", "activate_at": "0x7fffffffffffff", "pricing": { "linear": { "base": 999999, "word": 0 } } } }, - "0000000000000000000000000000000000000008": { "builtin": { "name": "bn128_pairing", "activate_at": "0x7fffffffffffff", "pricing": { "linear": { "base": 999999, "word": 0 } } } }, + "0000000000000000000000000000000000000005": { "builtin": { "name": "modexp", "activate_at": "0x7fffffffffffff", "pricing": { "modexp": { "divisor": 100 } } } }, + "0000000000000000000000000000000000000006": { "builtin": { "name": "alt_bn128_add", "activate_at": "0x7fffffffffffff", "pricing": { "linear": { "base": 500, "word": 0 } } } }, + "0000000000000000000000000000000000000007": { "builtin": { "name": "alt_bn128_mul", "activate_at": "0x7fffffffffffff", "pricing": { "linear": { "base": 2000, "word": 0 } } } }, + "0000000000000000000000000000000000000008": { "builtin": { "name": "alt_bn128_pairing", "activate_at": "0x7fffffffffffff", "pricing": { "alt_bn128_pairing": { "base": 100000, "pair": 80000 } } } }, "3282791d6fd713f1e94f4bfd565eaa78b3a0599d": { "balance": "1337000000000000000000" }, diff --git a/ethcore/res/ethereum/tests b/ethcore/res/ethereum/tests index ef191fdc6..9b722a014 160000 --- a/ethcore/res/ethereum/tests +++ b/ethcore/res/ethereum/tests @@ -1 +1 @@ -Subproject commit ef191fdc61cf76cdb9cdc147465fb447304b0ed2 +Subproject commit 9b722a014a2b2c9ea6eac456fe01a5c3dd1042a8 diff --git a/ethcore/res/ethereum/transition_test.json b/ethcore/res/ethereum/transition_test.json index 409210a76..064b651e2 100644 --- a/ethcore/res/ethereum/transition_test.json +++ b/ethcore/res/ethereum/transition_test.json @@ -1,136 +1,20 @@ { - "name": "EIP150.1b hard-fork consensus test", + "name": "Transition consensus test spec template", "engine": { "Ethash": { "params": { "minimumDifficulty": "0x020000", "difficultyBoundDivisor": "0x0800", "durationLimit": "0x0d", - "homesteadTransition": "0x5", - "daoHardforkTransition": "0x8", - "daoHardforkBeneficiary": "0xbf4ed7b27f1d666546e30d74d50d173d20bca754", - "daoHardforkAccounts": [ - "0xd4fe7bc31cedb7bfb8a345f31e668033056b2728", - "0xb3fb0e5aba0e20e5c49d252dfd30e102b171a425", - "0x2c19c7f9ae8b751e37aeb2d93a699722395ae18f", - "0xecd135fa4f61a655311e86238c92adcd779555d2", - "0x1975bd06d486162d5dc297798dfc41edd5d160a7", - "0xa3acf3a1e16b1d7c315e23510fdd7847b48234f6", - "0x319f70bab6845585f412ec7724b744fec6095c85", - "0x06706dd3f2c9abf0a21ddcc6941d9b86f0596936", - "0x5c8536898fbb74fc7445814902fd08422eac56d0", - "0x6966ab0d485353095148a2155858910e0965b6f9", - "0x779543a0491a837ca36ce8c635d6154e3c4911a6", - "0x2a5ed960395e2a49b1c758cef4aa15213cfd874c", - "0x5c6e67ccd5849c0d29219c4f95f1a7a93b3f5dc5", - "0x9c50426be05db97f5d64fc54bf89eff947f0a321", - "0x200450f06520bdd6c527622a273333384d870efb", - "0xbe8539bfe837b67d1282b2b1d61c3f723966f049", - "0x6b0c4d41ba9ab8d8cfb5d379c69a612f2ced8ecb", - "0xf1385fb24aad0cd7432824085e42aff90886fef5", - "0xd1ac8b1ef1b69ff51d1d401a476e7e612414f091", - "0x8163e7fb499e90f8544ea62bbf80d21cd26d9efd", - "0x51e0ddd9998364a2eb38588679f0d2c42653e4a6", - "0x627a0a960c079c21c34f7612d5d230e01b4ad4c7", - "0xf0b1aa0eb660754448a7937c022e30aa692fe0c5", - "0x24c4d950dfd4dd1902bbed3508144a54542bba94", - "0x9f27daea7aca0aa0446220b98d028715e3bc803d", - "0xa5dc5acd6a7968a4554d89d65e59b7fd3bff0f90", - "0xd9aef3a1e38a39c16b31d1ace71bca8ef58d315b", - "0x63ed5a272de2f6d968408b4acb9024f4cc208ebf", - "0x6f6704e5a10332af6672e50b3d9754dc460dfa4d", - "0x77ca7b50b6cd7e2f3fa008e24ab793fd56cb15f6", - "0x492ea3bb0f3315521c31f273e565b868fc090f17", - "0x0ff30d6de14a8224aa97b78aea5388d1c51c1f00", - "0x9ea779f907f0b315b364b0cfc39a0fde5b02a416", - "0xceaeb481747ca6c540a000c1f3641f8cef161fa7", - "0xcc34673c6c40e791051898567a1222daf90be287", - "0x579a80d909f346fbfb1189493f521d7f48d52238", - "0xe308bd1ac5fda103967359b2712dd89deffb7973", - "0x4cb31628079fb14e4bc3cd5e30c2f7489b00960c", - "0xac1ecab32727358dba8962a0f3b261731aad9723", - "0x4fd6ace747f06ece9c49699c7cabc62d02211f75", - "0x440c59b325d2997a134c2c7c60a8c61611212bad", - "0x4486a3d68fac6967006d7a517b889fd3f98c102b", - "0x9c15b54878ba618f494b38f0ae7443db6af648ba", - "0x27b137a85656544b1ccb5a0f2e561a5703c6a68f", - "0x21c7fdb9ed8d291d79ffd82eb2c4356ec0d81241", - "0x23b75c2f6791eef49c69684db4c6c1f93bf49a50", - "0x1ca6abd14d30affe533b24d7a21bff4c2d5e1f3b", - "0xb9637156d330c0d605a791f1c31ba5890582fe1c", - "0x6131c42fa982e56929107413a9d526fd99405560", - "0x1591fc0f688c81fbeb17f5426a162a7024d430c2", - "0x542a9515200d14b68e934e9830d91645a980dd7a", - "0xc4bbd073882dd2add2424cf47d35213405b01324", - "0x782495b7b3355efb2833d56ecb34dc22ad7dfcc4", - "0x58b95c9a9d5d26825e70a82b6adb139d3fd829eb", - "0x3ba4d81db016dc2890c81f3acec2454bff5aada5", - "0xb52042c8ca3f8aa246fa79c3feaa3d959347c0ab", - "0xe4ae1efdfc53b73893af49113d8694a057b9c0d1", - "0x3c02a7bc0391e86d91b7d144e61c2c01a25a79c5", - "0x0737a6b837f97f46ebade41b9bc3e1c509c85c53", - "0x97f43a37f595ab5dd318fb46e7a155eae057317a", - "0x52c5317c848ba20c7504cb2c8052abd1fde29d03", - "0x4863226780fe7c0356454236d3b1c8792785748d", - "0x5d2b2e6fcbe3b11d26b525e085ff818dae332479", - "0x5f9f3392e9f62f63b8eac0beb55541fc8627f42c", - "0x057b56736d32b86616a10f619859c6cd6f59092a", - "0x9aa008f65de0b923a2a4f02012ad034a5e2e2192", - "0x304a554a310c7e546dfe434669c62820b7d83490", - "0x914d1b8b43e92723e64fd0a06f5bdb8dd9b10c79", - "0x4deb0033bb26bc534b197e61d19e0733e5679784", - "0x07f5c1e1bc2c93e0402f23341973a0e043f7bf8a", - "0x35a051a0010aba705c9008d7a7eff6fb88f6ea7b", - "0x4fa802324e929786dbda3b8820dc7834e9134a2a", - "0x9da397b9e80755301a3b32173283a91c0ef6c87e", - "0x8d9edb3054ce5c5774a420ac37ebae0ac02343c6", - "0x0101f3be8ebb4bbd39a2e3b9a3639d4259832fd9", - "0x5dc28b15dffed94048d73806ce4b7a4612a1d48f", - "0xbcf899e6c7d9d5a215ab1e3444c86806fa854c76", - "0x12e626b0eebfe86a56d633b9864e389b45dcb260", - "0xa2f1ccba9395d7fcb155bba8bc92db9bafaeade7", - "0xec8e57756626fdc07c63ad2eafbd28d08e7b0ca5", - "0xd164b088bd9108b60d0ca3751da4bceb207b0782", - "0x6231b6d0d5e77fe001c2a460bd9584fee60d409b", - "0x1cba23d343a983e9b5cfd19496b9a9701ada385f", - "0xa82f360a8d3455c5c41366975bde739c37bfeb8a", - "0x9fcd2deaff372a39cc679d5c5e4de7bafb0b1339", - "0x005f5cee7a43331d5a3d3eec71305925a62f34b6", - "0x0e0da70933f4c7849fc0d203f5d1d43b9ae4532d", - "0xd131637d5275fd1a68a3200f4ad25c71a2a9522e", - "0xbc07118b9ac290e4622f5e77a0853539789effbe", - "0x47e7aa56d6bdf3f36be34619660de61275420af8", - "0xacd87e28b0c9d1254e868b81cba4cc20d9a32225", - "0xadf80daec7ba8dcf15392f1ac611fff65d94f880", - "0x5524c55fb03cf21f549444ccbecb664d0acad706", - "0x40b803a9abce16f50f36a77ba41180eb90023925", - "0xfe24cdd8648121a43a7c86d289be4dd2951ed49f", - "0x17802f43a0137c506ba92291391a8a8f207f487d", - "0x253488078a4edf4d6f42f113d1e62836a942cf1a", - "0x86af3e9626fce1957c82e88cbf04ddf3a2ed7915", - "0xb136707642a4ea12fb4bae820f03d2562ebff487", - "0xdbe9b615a3ae8709af8b93336ce9b477e4ac0940", - "0xf14c14075d6c4ed84b86798af0956deef67365b5", - "0xca544e5c4687d109611d0f8f928b53a25af72448", - "0xaeeb8ff27288bdabc0fa5ebb731b6f409507516c", - "0xcbb9d3703e651b0d496cdefb8b92c25aeb2171f7", - "0x6d87578288b6cb5549d5076a207456a1f6a63dc0", - "0xb2c6f0dfbb716ac562e2d85d6cb2f8d5ee87603e", - "0xaccc230e8a6e5be9160b8cdf2864dd2a001c28b6", - "0x2b3455ec7fedf16e646268bf88846bd7a2319bb2", - "0x4613f3bca5c44ea06337a9e439fbc6d42e501d0a", - "0xd343b217de44030afaa275f54d31a9317c7f441e", - "0x84ef4b2357079cd7a7c69fd7a37cd0609a679106", - "0xda2fef9e4a3230988ff17df2165440f37e8b1708", - "0xf4c64518ea10f995918a454158c6b61407ea345c", - "0x7602b46df5390e432ef1c307d4f2c9ff6d65cc97", - "0xbb9bc244d798123fde783fcc1c72d3bb8c189413", - "0x807640a13483f8ac783c557fcdf27be11ea4ac7a" - ], - "eip150Transition": "0xa", - "eip160Transition": "0x7fffffffffffffff", - "eip161abcTransition": "0x7fffffffffffffff", - "eip161dTransition": "0x7fffffffffffffff" + "homesteadTransition": "0", + "eip150Transition": "0", + "eip160Transition": "0", + "eip161abcTransition": "0", + "eip161dTransition": "0", + "maxCodeSize": 24576, + "eip649Reward": "0x29A2241AF62C0000", + "eip100bTransition": "5", + "eip649Transition": "5" } } }, @@ -142,9 +26,12 @@ "maximumExtraDataSize": "0x20", "minGasLimit": "0x1388", "networkID" : "0x1", - "eip98Transition": "0x7fffffffffffff", - "eip86Transition": "0x7fffffffffffff", - "eip155Transition": "0x7fffffffffffffff" + "eip98Transition": "5", + "eip140Transition": "5", + "eip211Transition": "5", + "eip214Transition": "5", + "eip155Transition": "5", + "eip658Transition": "5" }, "genesis": { "seal": { @@ -161,9 +48,13 @@ "gasLimit": "0x1388" }, "accounts": { - "0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, - "0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, - "0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, - "0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } } + "0000000000000000000000000000000000000001": { "balance": "1", "builtin": { "name": "ecrecover", "pricing": { "linear": { "base": 3000, "word": 0 } } } }, + "0000000000000000000000000000000000000002": { "balance": "1", "builtin": { "name": "sha256", "pricing": { "linear": { "base": 60, "word": 12 } } } }, + "0000000000000000000000000000000000000003": { "balance": "1", "builtin": { "name": "ripemd160", "pricing": { "linear": { "base": 600, "word": 120 } } } }, + "0000000000000000000000000000000000000004": { "balance": "1", "builtin": { "name": "identity", "pricing": { "linear": { "base": 15, "word": 3 } } } }, + "0000000000000000000000000000000000000005": { "builtin": { "name": "modexp", "activate_at": "5", "pricing": { "modexp": { "divisor": 100 } } } }, + "0000000000000000000000000000000000000006": { "builtin": { "name": "alt_bn128_add", "activate_at": "5", "pricing": { "linear": { "base": 500, "word": 0 } } } }, + "0000000000000000000000000000000000000007": { "builtin": { "name": "alt_bn128_mul", "activate_at": "5", "pricing": { "linear": { "base": 2000, "word": 0 } } } }, + "0000000000000000000000000000000000000008": { "builtin": { "name": "alt_bn128_pairing", "activate_at": "5", "pricing": { "alt_bn128_pairing": { "base": 100000, "pair": 80000 } } } } } } diff --git a/ethcore/src/blockchain/blockchain.rs b/ethcore/src/blockchain/blockchain.rs index 88bed91a3..7eb7a9f2d 100644 --- a/ethcore/src/blockchain/blockchain.rs +++ b/ethcore/src/blockchain/blockchain.rs @@ -2049,6 +2049,7 @@ mod tests { let bc = new_chain(&genesis, db.clone()); insert_block(&db, &bc, &b1, vec![Receipt { state_root: Some(H256::default()), + status_code: None, gas_used: 10_000.into(), log_bloom: Default::default(), logs: vec![ @@ -2058,6 +2059,7 @@ mod tests { }, Receipt { state_root: Some(H256::default()), + status_code: None, gas_used: 10_000.into(), log_bloom: Default::default(), logs: vec![ @@ -2067,6 +2069,7 @@ mod tests { insert_block(&db, &bc, &b2, vec![ Receipt { state_root: Some(H256::default()), + status_code: None, gas_used: 10_000.into(), log_bloom: Default::default(), logs: vec![ diff --git a/ethcore/src/builtin.rs b/ethcore/src/builtin.rs index 191e04dc6..9d3290a7c 100644 --- a/ethcore/src/builtin.rs +++ b/ethcore/src/builtin.rs @@ -64,7 +64,7 @@ struct Linear { } /// A special pricing model for modular exponentiation. -struct Modexp { +struct ModexpPricer { divisor: usize, } @@ -74,7 +74,20 @@ impl Pricer for Linear { } } -impl Pricer for Modexp { +/// A alt_bn128_parinig pricing model. This computes a price using a base cost and a cost per pair. +struct AltBn128PairingPricer { + base: usize, + pair: usize, +} + +impl Pricer for AltBn128PairingPricer { + fn cost(&self, input: &[u8]) -> U256 { + let cost = U256::from(self.base) + U256::from(self.pair) * U256::from(input.len() / 192); + cost + } +} + +impl Pricer for ModexpPricer { fn cost(&self, input: &[u8]) -> U256 { let mut reader = input.chain(io::repeat(0)); let mut buf = [0; 32]; @@ -88,17 +101,49 @@ impl Pricer for Modexp { let exp_len = read_len(); let mod_len = read_len(); - // floor(max(length_of_MODULUS, length_of_BASE) ** 2 * max(length_of_EXPONENT, 1) / GQUADDIVISOR) - // TODO: is saturating the best behavior here? + let max_len = U256::from(u32::max_value() / 2); + if base_len > max_len || mod_len > max_len { + return U256::max_value(); + } + + let base_len = base_len.low_u64(); + let exp_len = exp_len.low_u64(); + let mod_len = mod_len.low_u64(); let m = max(mod_len, base_len); - match m.overflowing_mul(m) { - (_, true) => U256::max_value(), - (val, _) => { - match val.overflowing_mul(max(exp_len, U256::one())) { - (_, true) => U256::max_value(), - (val, _) => val / (self.divisor as u64).into() - } - } + if m == 0 { + return U256::zero(); + } + // read fist 32-byte word of the exponent. + let exp_low = if base_len + 96 >= input.len() as u64 { U256::zero() } else { + let mut buf = [0; 32]; + let mut reader = input[(96 + base_len as usize)..].chain(io::repeat(0)); + let len = min(exp_len, 32) as usize; + reader.read_exact(&mut buf[(32 - len)..]).expect("reading from zero-extended memory cannot fail; qed"); + U256::from(H256::from_slice(&buf[..])) + }; + + let adjusted_exp_len = Self::adjusted_exp_len(exp_len, exp_low); + + (Self::mult_complexity(m) * max(adjusted_exp_len, 1) / self.divisor as u64).into() + } +} + +impl ModexpPricer { + fn adjusted_exp_len(len: u64, exp_low: U256) -> u64 { + let bit_index = if exp_low.is_zero() { 0 } else { (255 - exp_low.leading_zeros()) as u64 }; + if len <= 32 { + bit_index + } + else { + 8 * (len - 32) + bit_index + } + } + + fn mult_complexity(x: u64) -> u64 { + match x { + x if x <= 64 => x * x, + x if x <= 1024 => (x * x) / 4 + 96 * x - 3072, + x => (x * x) / 16 + 480 * x - 199680, } } } @@ -138,7 +183,7 @@ impl From for Builtin { }) } ethjson::spec::Pricing::Modexp(exp) => { - Box::new(Modexp { + Box::new(ModexpPricer { divisor: if exp.divisor == 0 { warn!("Zero modexp divisor specified. Falling back to default."); 10 @@ -147,6 +192,12 @@ impl From for Builtin { } }) } + ethjson::spec::Pricing::AltBn128Pairing(pricer) => { + Box::new(AltBn128PairingPricer { + base: pricer.base, + pair: pricer.pair, + }) + } }; Builtin { @@ -165,9 +216,9 @@ fn ethereum_builtin(name: &str) -> Box { "sha256" => Box::new(Sha256) as Box, "ripemd160" => Box::new(Ripemd160) as Box, "modexp" => Box::new(ModexpImpl) as Box, - "bn128_add" => Box::new(Bn128AddImpl) as Box, - "bn128_mul" => Box::new(Bn128MulImpl) as Box, - "bn128_pairing" => Box::new(Bn128PairingImpl) as Box, + "alt_bn128_add" => Box::new(Bn128AddImpl) as Box, + "alt_bn128_mul" => Box::new(Bn128MulImpl) as Box, + "alt_bn128_pairing" => Box::new(Bn128PairingImpl) as Box, _ => panic!("invalid builtin name: {}", name), } } @@ -273,11 +324,16 @@ impl Impl for Ripemd160 { fn modexp(mut base: BigUint, mut exp: BigUint, modulus: BigUint) -> BigUint { use num::Integer; - match (base.is_zero(), exp.is_zero()) { - (_, true) => return BigUint::one(), // n^0 % m - (true, false) => return BigUint::zero(), // 0^n % m, n>0 - (false, false) if modulus <= BigUint::one() => return BigUint::zero(), // a^b % 1 = 0. - _ => {} + if modulus <= BigUint::one() { // n^m % 0 || n^m % 1 + return BigUint::zero(); + } + + if exp.is_zero() { // n^0 % m + return BigUint::one(); + } + + if base.is_zero() { // 0^n % m, n>0 + return BigUint::zero(); } let mut result = BigUint::one(); @@ -293,7 +349,6 @@ fn modexp(mut base: BigUint, mut exp: BigUint, modulus: BigUint) -> BigUint { exp = exp >> 1; base = (base.clone() * base) % &modulus; } - result } @@ -314,19 +369,25 @@ impl Impl for ModexpImpl { let exp_len = read_len(&mut reader); let mod_len = read_len(&mut reader); - // read the numbers themselves. - let mut buf = vec![0; max(mod_len, max(base_len, exp_len))]; - let mut read_num = |len| { - reader.read_exact(&mut buf[..len]).expect("reading from zero-extended memory cannot fail; qed"); - BigUint::from_bytes_be(&buf[..len]) + // Gas formula allows arbitrary large exp_len when base and modulus are empty, so we need to handle empty base first. + let r = if base_len == 0 && mod_len == 0 { + BigUint::zero() + } else { + // read the numbers themselves. + let mut buf = vec![0; max(mod_len, max(base_len, exp_len))]; + let mut read_num = |len| { + reader.read_exact(&mut buf[..len]).expect("reading from zero-extended memory cannot fail; qed"); + BigUint::from_bytes_be(&buf[..len]) + }; + + let base = read_num(base_len); + let exp = read_num(exp_len); + let modulus = read_num(mod_len); + modexp(base, exp, modulus) }; - let base = read_num(base_len); - let exp = read_num(exp_len); - let modulus = read_num(mod_len); - // write output to given memory, left padded and same length as the modulus. - let bytes = modexp(base, exp, modulus).to_bytes_be(); + let bytes = r.to_bytes_be(); // always true except in the case of zero-length modulus, which leads to // output of length and value 1. @@ -356,7 +417,6 @@ fn read_point(reader: &mut io::Chain<&[u8], io::Repeat>) -> Result<::bn::G1, Err reader.read_exact(&mut buf[..]).expect("reading from zero-extended memory cannot fail; qed"); let py = Fq::from_slice(&buf[0..32]).map_err(|_| Error::from("Invalid point y coordinate"))?; - Ok( if px == Fq::zero() && py == Fq::zero() { G1::zero() @@ -407,50 +467,29 @@ impl Impl for Bn128MulImpl { } } -mod bn128_gen { - use bn::{AffineG1, AffineG2, Fq, Fq2, G1, G2, Gt, pairing}; - - lazy_static! { - pub static ref P1: G1 = G1::from(AffineG1::new( - Fq::from_str("1").expect("1 is a valid field element"), - Fq::from_str("2").expect("2 is a valid field element"), - ).expect("Generator P1(1, 2) is a valid curve point")); - } - - lazy_static! { - pub static ref P2: G2 = G2::from(AffineG2::new( - Fq2::new( - Fq::from_str("10857046999023057135944570762232829481370756359578518086990519993285655852781") - .expect("a valid field element"), - Fq::from_str("11559732032986387107991004021392285783925812861821192530917403151452391805634") - .expect("a valid field element"), - ), - Fq2::new( - Fq::from_str("8495653923123431417604973247489272438418190587263600148770280649306958101930") - .expect("a valid field element"), - Fq::from_str("4082367875863433681332203403145435568316851327593401208105741076214120093531") - .expect("a valid field element"), - ), - ).expect("the generator P2(10857046999023057135944570762232829481370756359578518086990519993285655852781 + 11559732032986387107991004021392285783925812861821192530917403151452391805634i, 8495653923123431417604973247489272438418190587263600148770280649306958101930 + 4082367875863433681332203403145435568316851327593401208105741076214120093531i) is a valid curve point")); - } - - lazy_static! { - pub static ref P1_P2_PAIRING: Gt = pairing(P1.clone(), P2.clone()); - } -} - impl Impl for Bn128PairingImpl { /// Can fail if: /// - input length is not a multiple of 192 /// - any of odd points does not belong to bn128 curve /// - any of even points does not belong to the twisted bn128 curve over the field F_p^2 = F_p[i] / (i^2 + 1) fn execute(&self, input: &[u8], output: &mut BytesRef) -> Result<(), Error> { - use bn::{AffineG1, AffineG2, Fq, Fq2, pairing, G1, G2, Gt}; - - let elements = input.len() / 192; // (a, b_a, b_b - each 64-byte affine coordinates) if input.len() % 192 != 0 { return Err("Invalid input length, must be multiple of 192 (3 * (32*2))".into()) } + + if let Err(err) = self.execute_with_error(input, output) { + trace!("Pairining error: {:?}", err); + return Err(err) + } + Ok(()) + } +} + +impl Bn128PairingImpl { + fn execute_with_error(&self, input: &[u8], output: &mut BytesRef) -> Result<(), Error> { + use bn::{AffineG1, AffineG2, Fq, Fq2, pairing, G1, G2, Gt, Group}; + + let elements = input.len() / 192; // (a, b_a, b_b - each 64-byte affine coordinates) let ret_val = if input.len() == 0 { U256::one() } else { @@ -462,34 +501,36 @@ impl Impl for Bn128PairingImpl { let a_y = Fq::from_slice(&input[idx*192+32..idx*192+64]) .map_err(|_| Error::from("Invalid a argument y coordinate"))?; - let b_b_x = Fq::from_slice(&input[idx*192+64..idx*192+96]) + let b_a_y = Fq::from_slice(&input[idx*192+64..idx*192+96]) .map_err(|_| Error::from("Invalid b argument imaginary coeff x coordinate"))?; - let b_b_y = Fq::from_slice(&input[idx*192+96..idx*192+128]) + let b_a_x = Fq::from_slice(&input[idx*192+96..idx*192+128]) .map_err(|_| Error::from("Invalid b argument imaginary coeff y coordinate"))?; - let b_a_x = Fq::from_slice(&input[idx*192+128..idx*192+160]) + let b_b_y = Fq::from_slice(&input[idx*192+128..idx*192+160]) .map_err(|_| Error::from("Invalid b argument real coeff x coordinate"))?; - let b_a_y = Fq::from_slice(&input[idx*192+160..idx*192+192]) + let b_b_x = Fq::from_slice(&input[idx*192+160..idx*192+192]) .map_err(|_| Error::from("Invalid b argument real coeff y coordinate"))?; - vals.push(( - G1::from( - AffineG1::new(a_x, a_y).map_err(|_| Error::from("Invalid a argument - not on curve"))? - ), - G2::from( - AffineG2::new( - Fq2::new(b_a_x, b_a_y), - Fq2::new(b_b_x, b_b_y), - ).map_err(|_| Error::from("Invalid b argument - not on curve"))? - ), - )); + let b_a = Fq2::new(b_a_x, b_a_y); + let b_b = Fq2::new(b_b_x, b_b_y); + let b = if b_a.is_zero() && b_b.is_zero() { + G2::zero() + } else { + G2::from(AffineG2::new(b_a, b_b).map_err(|_| Error::from("Invalid b argument - not on curve"))?) + }; + let a = if a_x.is_zero() && a_y.is_zero() { + G1::zero() + } else { + G1::from(AffineG1::new(a_x, a_y).map_err(|_| Error::from("Invalid a argument - not on curve"))?) + }; + vals.push((a, b)); }; let mul = vals.into_iter().fold(Gt::one(), |s, (a, b)| s * pairing(a, b)); - if mul == *bn128_gen::P1_P2_PAIRING { + if mul == Gt::one() { U256::one() } else { U256::zero() @@ -506,7 +547,7 @@ impl Impl for Bn128PairingImpl { #[cfg(test)] mod tests { - use super::{Builtin, Linear, ethereum_builtin, Pricer, Modexp, modexp as me}; + use super::{Builtin, Linear, ethereum_builtin, Pricer, ModexpPricer, modexp as me}; use ethjson; use bigint::prelude::U256; use bytes::BytesRef; @@ -662,7 +703,7 @@ mod tests { fn modexp() { let f = Builtin { - pricer: Box::new(Modexp { divisor: 20 }), + pricer: Box::new(ModexpPricer { divisor: 20 }), native: ethereum_builtin("modexp"), activate_at: 0, }; @@ -679,7 +720,7 @@ mod tests { let mut output = vec![0u8; 32]; let expected = FromHex::from_hex("0000000000000000000000000000000000000000000000000000000000000001").unwrap(); - let expected_cost = 1638; + let expected_cost = 13056; f.execute(&input[..], &mut BytesRef::Fixed(&mut output[..])).expect("Builtin should not fail"); assert_eq!(output, expected); @@ -690,15 +731,15 @@ mod tests { { let input = FromHex::from_hex("\ 0000000000000000000000000000000000000000000000000000000000000000\ - 0000000000000000000000000000000000000000000000000000000000000020\ - 0000000000000000000000000000000000000000000000000000000000000020\ - fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\ - fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f" + 0000000000000000000000000000000000000000000000000000000000000020\ + 0000000000000000000000000000000000000000000000000000000000000020\ + fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2e\ + fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f" ).unwrap(); let mut output = vec![0u8; 32]; let expected = FromHex::from_hex("0000000000000000000000000000000000000000000000000000000000000000").unwrap(); - let expected_cost = 1638; + let expected_cost = 13056; f.execute(&input[..], &mut BytesRef::Fixed(&mut output[..])).expect("Builtin should not fail"); assert_eq!(output, expected); @@ -718,7 +759,7 @@ mod tests { let mut output = vec![0u8; 32]; let expected = FromHex::from_hex("3b01b01ac41f2d6e917c6d6a221ce793802469026d9ab7578fa2e79e4da6aaab").unwrap(); - let expected_cost = 102; + let expected_cost = 768; f.execute(&input[..], &mut BytesRef::Fixed(&mut output[..])).expect("Builtin should not fail"); assert_eq!(output, expected); @@ -749,7 +790,7 @@ mod tests { let f = Builtin { pricer: Box::new(Linear { base: 0, word: 0 }), - native: ethereum_builtin("bn128_add"), + native: ethereum_builtin("alt_bn128_add"), activate_at: 0, }; @@ -810,7 +851,7 @@ mod tests { let f = Builtin { pricer: Box::new(Linear { base: 0, word: 0 }), - native: ethereum_builtin("bn128_mul"), + native: ethereum_builtin("alt_bn128_mul"), activate_at: 0, }; @@ -850,7 +891,7 @@ mod tests { fn builtin_pairing() -> Builtin { Builtin { pricer: Box::new(Linear { base: 0, word: 0 }), - native: ethereum_builtin("bn128_pairing"), + native: ethereum_builtin("alt_bn128_pairing"), activate_at: 0, } } diff --git a/ethcore/src/client/client.rs b/ethcore/src/client/client.rs index 9fe9a4573..8659ade6f 100644 --- a/ethcore/src/client/client.rs +++ b/ethcore/src/client/client.rs @@ -2140,11 +2140,13 @@ mod tests { }]; let receipts = vec![Receipt { state_root: state_root, + status_code: None, gas_used: 5.into(), log_bloom: Default::default(), logs: vec![logs[0].clone()], }, Receipt { state_root: state_root, + status_code: None, gas_used: gas_used, log_bloom: Default::default(), logs: logs.clone(), diff --git a/ethcore/src/client/evm_test_client.rs b/ethcore/src/client/evm_test_client.rs index 2c465a24b..db1a11f79 100644 --- a/ethcore/src/client/evm_test_client.rs +++ b/ethcore/src/client/evm_test_client.rs @@ -26,7 +26,7 @@ use bytes; use util::kvdb::{self, KeyValueDB}; use {state, state_db, client, executive, trace, transaction, db, spec, pod_state}; use factory::Factories; -use evm::{self, VMType}; +use evm::{self, VMType, FinalizationResult}; use vm::{self, ActionParams}; /// EVM test Error. @@ -72,7 +72,8 @@ lazy_static! { pub static ref HOMESTEAD: spec::Spec = ethereum::new_homestead_test(); pub static ref EIP150: spec::Spec = ethereum::new_eip150_test(); pub static ref EIP161: spec::Spec = ethereum::new_eip161_test(); - pub static ref _METROPOLIS: spec::Spec = ethereum::new_metropolis_test(); + pub static ref BYZANTIUM: spec::Spec = ethereum::new_byzantium_test(); + pub static ref BYZANTIUM_TRANSITION: spec::Spec = ethereum::new_transition_test(); } /// Simplified, single-block EVM test client. @@ -89,7 +90,10 @@ impl<'a> EvmTestClient<'a> { ForkSpec::Homestead => Some(&*HOMESTEAD), ForkSpec::EIP150 => Some(&*EIP150), ForkSpec::EIP158 => Some(&*EIP161), - ForkSpec::Metropolis | ForkSpec::Byzantium | ForkSpec::Constantinople => None, + ForkSpec::Byzantium => Some(&*BYZANTIUM), + ForkSpec::EIP158ToByzantiumAt5 => Some(&BYZANTIUM_TRANSITION), + ForkSpec::FrontierToHomesteadAt5 | ForkSpec::HomesteadToDaoAt5 | ForkSpec::HomesteadToEIP150At5 => None, + _ => None, } } @@ -162,7 +166,7 @@ impl<'a> EvmTestClient<'a> { /// Execute the VM given ActionParams and tracer. /// Returns amount of gas left and the output. pub fn call(&mut self, params: ActionParams, vm_tracer: &mut T) - -> Result<(U256, Vec), EvmTestError> + -> Result { let genesis = self.spec.genesis_header(); let info = client::EnvInfo { @@ -178,15 +182,13 @@ impl<'a> EvmTestClient<'a> { let mut tracer = trace::NoopTracer; let mut output = vec![]; let mut executive = executive::Executive::new(&mut self.state, &info, &*self.spec.engine); - let (gas_left, _) = executive.call( + executive.call( params, &mut substate, bytes::BytesRef::Flexible(&mut output), &mut tracer, vm_tracer, - ).map_err(EvmTestError::Evm)?; - - Ok((gas_left, output)) + ).map_err(EvmTestError::Evm) } /// Executes a SignedTransaction within context of the provided state and `EnvInfo`. @@ -212,10 +214,13 @@ impl<'a> EvmTestClient<'a> { let result = self.state.apply_with_tracing(&env_info, &*self.spec.engine, &transaction, tracer, vm_tracer); match result { - Ok(result) => TransactResult::Ok { - state_root: *self.state.root(), - gas_left: initial_gas - result.receipt.gas_used, - output: result.output + Ok(result) => { + self.state.commit().ok(); + TransactResult::Ok { + state_root: *self.state.root(), + gas_left: initial_gas - result.receipt.gas_used, + output: result.output + } }, Err(error) => TransactResult::Err { state_root: *self.state.root(), diff --git a/ethcore/src/client/test_client.rs b/ethcore/src/client/test_client.rs index eb3706e01..5052b67d6 100644 --- a/ethcore/src/client/test_client.rs +++ b/ethcore/src/client/test_client.rs @@ -619,6 +619,7 @@ impl BlockChainClient for TestBlockChainClient { if *hash > H256::from("f000000000000000000000000000000000000000000000000000000000000000") { let receipt = BlockReceipts::new(vec![Receipt::new( Some(H256::zero()), + None, U256::zero(), vec![])]); let mut rlp = RlpStream::new(); diff --git a/ethcore/src/engines/mod.rs b/ethcore/src/engines/mod.rs index b48ff2f3f..50f787c2b 100644 --- a/ethcore/src/engines/mod.rs +++ b/ethcore/src/engines/mod.rs @@ -62,8 +62,8 @@ use unexpected::{Mismatch, OutOfBounds}; use bytes::Bytes; /// Default EIP-210 contrat code. -/// As defined in https://github.com/ethereum/EIPs/pull/210/commits/9df24a3714af42e3bf350265bdc75b486c909d7f#diff-e02a92c2fb96c1a1bfb05e4c6e2ef5daR49 -pub const DEFAULT_BLOCKHASH_CONTRACT: &'static str = "73fffffffffffffffffffffffffffffffffffffffe33141561007a57600143036020526000356101006020510755600061010060205107141561005057600035610100610100602051050761010001555b6000620100006020510714156100755760003561010062010000602051050761020001555b610161565b436000351215801561008c5780610095565b623567e0600035125b9050156100a757600060605260206060f35b610100600035430312156100ca57610100600035075460805260206080f3610160565b62010000600035430312156100e857600061010060003507146100eb565b60005b1561010d576101006101006000350507610100015460a052602060a0f361015f565b63010000006000354303121561012d576000620100006000350714610130565b60005b1561015357610100620100006000350507610200015460c052602060c0f361015e565b600060e052602060e0f35b5b5b5b5b"; +/// As defined in https://github.com/ethereum/EIPs/pull/210 +pub const DEFAULT_BLOCKHASH_CONTRACT: &'static str = "73fffffffffffffffffffffffffffffffffffffffe33141561006a5760014303600035610100820755610100810715156100455760003561010061010083050761010001555b6201000081071515610064576000356101006201000083050761020001555b5061013e565b4360003512151561008457600060405260206040f361013d565b61010060003543031315156100a857610100600035075460605260206060f361013c565b6101006000350715156100c55762010000600035430313156100c8565b60005b156100ea576101006101006000350507610100015460805260206080f361013b565b620100006000350715156101095763010000006000354303131561010c565b60005b1561012f57610100620100006000350507610200015460a052602060a0f361013a565b600060c052602060c0f35b5b5b5b5b"; /// Voting errors. #[derive(Debug)] diff --git a/ethcore/src/ethereum/ethash.rs b/ethcore/src/ethereum/ethash.rs index 11c04b628..91e326b64 100644 --- a/ethcore/src/ethereum/ethash.rs +++ b/ethcore/src/ethereum/ethash.rs @@ -51,6 +51,7 @@ const SNAPSHOT_BLOCKS: u64 = 5000; /// Maximum number of blocks allowed in an ethash snapshot. const MAX_SNAPSHOT_BLOCKS: u64 = 30000; +const DEFAULT_EIP649_DELAY: u64 = 3_000_000; /// Ethash params. #[derive(Debug, PartialEq)] @@ -105,6 +106,12 @@ pub struct EthashParams { pub min_gas_price_transition: u64, /// Do not alow transactions with lower gas price. pub min_gas_price: U256, + /// EIP-649 transition block. + pub eip649_transition: u64, + /// EIP-649 bomb delay. + pub eip649_delay: u64, + /// EIP-649 base reward. + pub eip649_reward: Option, } impl From for EthashParams { @@ -135,6 +142,9 @@ impl From for EthashParams { max_gas_limit: p.max_gas_limit.map_or(U256::max_value(), Into::into), min_gas_price_transition: p.min_gas_price_transition.map_or(u64::max_value(), Into::into), min_gas_price: p.min_gas_price.map_or(U256::zero(), Into::into), + eip649_transition: p.eip649_transition.map_or(u64::max_value(), Into::into), + eip649_delay: p.eip649_delay.map_or(DEFAULT_EIP649_DELAY, Into::into), + eip649_reward: p.eip649_reward.map(Into::into), } } } @@ -215,8 +225,10 @@ impl Engine for Arc { } else if block_number < self.ethash_params.eip150_transition { Schedule::new_homestead() } else { + /// There's no max_code_size transition so we tie it to eip161abc + let max_code_size = if block_number >= self.ethash_params.eip161abc_transition { self.ethash_params.max_code_size as usize } else { usize::max_value() }; let mut schedule = Schedule::new_post_eip150( - self.ethash_params.max_code_size as usize, + max_code_size, block_number >= self.ethash_params.eip160_transition, block_number >= self.ethash_params.eip161abc_transition, block_number >= self.ethash_params.eip161d_transition); @@ -296,9 +308,14 @@ impl Engine for Arc { /// This assumes that all uncles are valid uncles (i.e. of at least one generation before the current). fn on_close_block(&self, block: &mut ExecutedBlock) -> Result<(), Error> { use std::ops::Shr; - let reward = self.params().block_reward; let tracing_enabled = block.tracing_enabled(); let fields = block.fields_mut(); + let reward = if fields.header.number() >= self.ethash_params.eip649_transition { + self.ethash_params.eip649_reward.unwrap_or(self.params().block_reward) + } else { + self.params().block_reward + }; + let eras_rounds = self.ethash_params.ecip1017_era_rounds; let (eras, reward) = ecip1017_eras_block_reward(eras_rounds, reward, fields.header.number()); let mut tracer = ExecutiveTracer::default(); @@ -500,7 +517,7 @@ fn ecip1017_eras_block_reward(era_rounds: u64, mut reward: U256, block_number:u6 #[cfg_attr(feature="dev", allow(wrong_self_convention))] impl Ethash { fn calculate_difficulty(&self, header: &Header, parent: &Header) -> U256 { - const EXP_DIFF_PERIOD: u64 = 100000; + const EXP_DIFF_PERIOD: u64 = 100_000; if header.number() == 0 { panic!("Can't calculate genesis block difficulty"); } @@ -550,7 +567,11 @@ impl Ethash { target = cmp::max(min_difficulty, target); if header.number() < self.ethash_params.bomb_defuse_transition { if header.number() < self.ethash_params.ecip1010_pause_transition { - let period = ((parent.number() + 1) / EXP_DIFF_PERIOD) as usize; + let mut number = header.number(); + if number >= self.ethash_params.eip649_transition { + number = number.saturating_sub(self.ethash_params.eip649_delay); + } + let period = (number / EXP_DIFF_PERIOD) as usize; if period > 1 { target = cmp::max(min_difficulty, target + (U256::from(1) << (period - 2))); } diff --git a/ethcore/src/ethereum/mod.rs b/ethcore/src/ethereum/mod.rs index 8cc9446a6..2135ea267 100644 --- a/ethcore/src/ethereum/mod.rs +++ b/ethcore/src/ethereum/mod.rs @@ -87,8 +87,11 @@ pub fn new_transition_test() -> Spec { load(None, include_bytes!("../../res/ethe /// Create a new Foundation Mainnet chain spec without genesis accounts. pub fn new_mainnet_like() -> Spec { load(None, include_bytes!("../../res/ethereum/frontier_like_test.json")) } -/// Create a new Foundation Metropolis era spec. -pub fn new_metropolis_test() -> Spec { load(None, include_bytes!("../../res/ethereum/metropolis_test.json")) } +/// Create a new Foundation Byzantium era spec. +pub fn new_byzantium_test() -> Spec { load(None, include_bytes!("../../res/ethereum/byzantium_test.json")) } + +/// Create a new Foundation Constantinople era spec. +pub fn new_constantinople_test() -> Spec { load(None, include_bytes!("../../res/ethereum/constantinople_test.json")) } #[cfg(test)] mod tests { diff --git a/ethcore/src/executive.rs b/ethcore/src/executive.rs index 98ead0b8e..38239b4a4 100644 --- a/ethcore/src/executive.rs +++ b/ethcore/src/executive.rs @@ -291,7 +291,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { let mut substate = Substate::new(); // NOTE: there can be no invalid transactions from this point. - if !t.is_unsigned() { + if !schedule.eip86 || !t.is_unsigned() { self.state.inc_nonce(&sender)?; } self.state.sub_balance(&sender, &U256::from(gas_cost), &mut substate.to_cleanup_mode(&schedule))?; @@ -383,12 +383,12 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { mut output: BytesRef, tracer: &mut T, vm_tracer: &mut V - ) -> vm::Result<(U256, ReturnData)> where T: Tracer, V: VMTracer { + ) -> vm::Result where T: Tracer, V: VMTracer { - trace!("Executive::call(params={:?}) self.env_info={:?}", params, self.info); + trace!("Executive::call(params={:?}) self.env_info={:?}, static={}", params, self.info, self.static_flag); if (params.call_type == CallType::StaticCall || - ((params.call_type == CallType::Call || params.call_type == CallType::DelegateCall) && - self.static_flag)) + ((params.call_type == CallType::Call) && + self.static_flag)) && params.value.value() > 0.into() { return Err(vm::Error::MutableCallInStaticContext); } @@ -441,7 +441,11 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { ); } - Ok((params.gas - cost, ReturnData::empty())) + Ok(FinalizationResult { + gas_left: params.gas - cost, + return_data: ReturnData::new(output.to_owned(), 0, output.len()), + apply_state: true, + }) } } else { // just drain the whole gas @@ -488,13 +492,17 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { self.enact_result(&res, substate, unconfirmed_substate); trace!(target: "executive", "enacted: substate={:?}\n", substate); - res.map(|r| (r.gas_left, r.return_data)) + res } else { // otherwise it's just a basic transaction, only do tracing, if necessary. self.state.discard_checkpoint(); tracer.trace_call(trace_info, U256::zero(), trace_output, vec![]); - Ok((params.gas, ReturnData::empty())) + Ok(FinalizationResult { + gas_left: params.gas, + return_data: ReturnData::empty(), + apply_state: true, + }) } } } @@ -509,13 +517,18 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { output: &mut Option, tracer: &mut T, vm_tracer: &mut V, - ) -> vm::Result<(U256, ReturnData)> where T: Tracer, V: VMTracer { + ) -> vm::Result where T: Tracer, V: VMTracer { - let scheme = self.engine.create_address_scheme(self.info.number); - if scheme != CreateContractAddress::FromSenderAndNonce && self.state.exists_and_has_code(¶ms.address)? { + // EIP-684: If a contract creation is attempted, due to either a creation transaction or the + // CREATE (or future CREATE2) opcode, and the destination address already has either + // nonzero nonce, or nonempty code, then the creation throws immediately, with exactly + // the same behavior as would arise if the first byte in the init code were an invalid + // opcode. This applies retroactively starting from genesis. + if self.state.exists_and_has_code_or_nonce(¶ms.address)? { return Err(vm::Error::OutOfGas); } + trace!("Executive::create(params={:?}) self.env_info={:?}, static={}", params, self.info, self.static_flag); if params.call_type == CallType::StaticCall || self.static_flag { let trace_info = tracer.prepare_trace_create(¶ms); tracer.trace_failed_create(trace_info, vec![], vm::Error::MutableCallInStaticContext.into()); @@ -565,7 +578,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { }; self.enact_result(&res, substate, unconfirmed_substate); - res.map(|r| (r.gas_left, r.return_data)) + res } /// Finalizes the transaction (does refunds and suicides). @@ -573,7 +586,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { &mut self, t: &SignedTransaction, mut substate: Substate, - result: vm::Result<(U256, ReturnData)>, + result: vm::Result, output: Bytes, trace: Vec, vm_trace: Option @@ -587,7 +600,7 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { let refunds_bound = sstore_refunds + suicide_refunds; // real ammount to refund - let gas_left_prerefund = match result { Ok((x, _)) => x, _ => 0.into() }; + let gas_left_prerefund = match result { Ok(FinalizationResult{ gas_left, .. }) => gas_left, _ => 0.into() }; let refunded = cmp::min(refunds_bound, (t.gas - gas_left_prerefund) >> 1); let gas_left = gas_left_prerefund + refunded; @@ -631,9 +644,9 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { state_diff: None, }) }, - _ => { + Ok(r) => { Ok(Executed { - exception: None, + exception: if r.apply_state { None } else { Some(vm::Error::Reverted) }, gas: t.gas, gas_used: gas_used, refunded: refunded, @@ -659,6 +672,8 @@ impl<'a, B: 'a + StateBackend, E: Engine + ?Sized> Executive<'a, B, E> { | Err(vm::Error::Wasm {..}) | Err(vm::Error::OutOfStack {..}) | Err(vm::Error::MutableCallInStaticContext) + | Err(vm::Error::OutOfBounds) + | Err(vm::Error::Reverted) | Ok(FinalizationResult { apply_state: false, .. }) => { self.state.revert_to_checkpoint(); }, @@ -716,7 +731,7 @@ mod tests { let engine = TestEngine::new(0); let mut substate = Substate::new(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.create(params, &mut substate, &mut None, &mut NoopTracer, &mut NoopVMTracer).unwrap() }; @@ -774,7 +789,7 @@ mod tests { let engine = TestEngine::new(0); let mut substate = Substate::new(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.create(params, &mut substate, &mut None, &mut NoopTracer, &mut NoopVMTracer).unwrap() }; @@ -832,7 +847,7 @@ mod tests { let mut tracer = ExecutiveTracer::default(); let mut vm_tracer = ExecutiveVMTracer::toplevel(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); let output = BytesRef::Fixed(&mut[0u8;0]); ex.call(params, &mut substate, output, &mut tracer, &mut vm_tracer).unwrap() @@ -941,7 +956,7 @@ mod tests { let mut tracer = ExecutiveTracer::default(); let mut vm_tracer = ExecutiveVMTracer::toplevel(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.create(params.clone(), &mut substate, &mut None, &mut tracer, &mut vm_tracer).unwrap() }; @@ -1026,7 +1041,7 @@ mod tests { let engine = TestEngine::new(0); let mut substate = Substate::new(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.create(params, &mut substate, &mut None, &mut NoopTracer, &mut NoopVMTracer).unwrap() }; @@ -1137,7 +1152,7 @@ mod tests { let engine = TestEngine::new(0); let mut substate = Substate::new(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.call(params, &mut substate, BytesRef::Fixed(&mut []), &mut NoopTracer, &mut NoopVMTracer).unwrap() }; @@ -1181,7 +1196,7 @@ mod tests { let engine = TestEngine::new(0); let mut substate = Substate::new(); - let (gas_left, _) = { + let FinalizationResult { gas_left, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.call(params, &mut substate, BytesRef::Fixed(&mut []), &mut NoopTracer, &mut NoopVMTracer).unwrap() }; @@ -1382,11 +1397,11 @@ mod tests { let mut state = get_temp_state_with_factory(factory); state.add_balance(&sender, &U256::from_str("152d02c7e14af68000000").unwrap(), CleanupMode::NoEmpty).unwrap(); let info = EnvInfo::default(); - let engine = TestEngine::new_metropolis(); + let engine = TestEngine::new_byzantium(); let mut substate = Substate::new(); let mut output = [0u8; 14]; - let (result, _) = { + let FinalizationResult { gas_left: result, .. } = { let mut ex = Executive::new(&mut state, &info, &engine); ex.call(params, &mut substate, BytesRef::Fixed(&mut output), &mut NoopTracer, &mut NoopVMTracer).unwrap() }; diff --git a/ethcore/src/externalities.rs b/ethcore/src/externalities.rs index b84fbfe5b..d429f1277 100644 --- a/ethcore/src/externalities.rs +++ b/ethcore/src/externalities.rs @@ -29,6 +29,7 @@ use vm::{ Ext, ContractCreateResult, MessageCallResult, CreateContractAddress, ReturnData }; +use evm::FinalizationResult; use transaction::UNSIGNED_SENDER; use trace::{Tracer, VMTracer}; @@ -127,6 +128,10 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> } } + fn is_static(&self) -> bool { + return self.static_flag + } + fn exists(&self, address: &Address) -> vm::Result { self.state.exists(address).map_err(Into::into) } @@ -216,21 +221,27 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> call_type: CallType::None, }; - if params.sender != UNSIGNED_SENDER { - if let Err(e) = self.state.inc_nonce(&self.origin_info.address) { - debug!(target: "ext", "Database corruption encountered: {:?}", e); - return ContractCreateResult::Failed + if !self.static_flag { + if !self.schedule.eip86 || params.sender != UNSIGNED_SENDER { + if let Err(e) = self.state.inc_nonce(&self.origin_info.address) { + debug!(target: "ext", "Database corruption encountered: {:?}", e); + return ContractCreateResult::Failed + } } } let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth, self.static_flag); // TODO: handle internal error separately match ex.create(params, self.substate, &mut None, self.tracer, self.vm_tracer) { - Ok((gas_left, _)) => { + Ok(FinalizationResult{ gas_left, apply_state: true, .. }) => { self.substate.contracts_created.push(address.clone()); ContractCreateResult::Created(address, gas_left) }, - _ => ContractCreateResult::Failed + Ok(FinalizationResult{ gas_left, apply_state: false, return_data }) => { + ContractCreateResult::Reverted(gas_left, return_data) + }, + Err(vm::Error::MutableCallInStaticContext) => ContractCreateResult::FailedInStaticCall, + _ => ContractCreateResult::Failed, } } @@ -275,7 +286,8 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> let mut ex = Executive::from_parent(self.state, self.env_info, self.engine, self.depth, self.static_flag); match ex.call(params, self.substate, BytesRef::Fixed(output), self.tracer, self.vm_tracer) { - Ok((gas_left, return_data)) => MessageCallResult::Success(gas_left, return_data), + Ok(FinalizationResult{ gas_left, return_data, apply_state: true }) => MessageCallResult::Success(gas_left, return_data), + Ok(FinalizationResult{ gas_left, return_data, apply_state: false }) => MessageCallResult::Reverted(gas_left, return_data), _ => MessageCallResult::Failed } } @@ -289,7 +301,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> } #[cfg_attr(feature="dev", allow(match_ref_pats))] - fn ret(mut self, gas: &U256, data: &ReturnData) -> vm::Result + fn ret(mut self, gas: &U256, data: &ReturnData, apply_state: bool) -> vm::Result where Self: Sized { let handle_copy = |to: &mut Option<&mut Bytes>| { to.as_mut().map(|b| **b = data.to_vec()); @@ -309,7 +321,7 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> vec.extend_from_slice(&*data); Ok(*gas) }, - OutputPolicy::InitContract(ref mut copy) => { + OutputPolicy::InitContract(ref mut copy) if apply_state => { let return_cost = U256::from(data.len()) * U256::from(self.schedule.create_data_gas); if return_cost > *gas || data.len() > self.schedule.create_data_limit { return match self.schedule.exceptional_failed_code_deposit { @@ -317,12 +329,13 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for Externalities<'a, T, V, B, E> false => Ok(*gas) } } - handle_copy(copy); - self.state.init_code(&self.origin_info.address, data.to_vec())?; Ok(*gas - return_cost) - } + }, + OutputPolicy::InitContract(_) => { + Ok(*gas) + }, } } diff --git a/ethcore/src/json_tests/chain.rs b/ethcore/src/json_tests/chain.rs index 7047c9882..9ae55f73d 100644 --- a/ethcore/src/json_tests/chain.rs +++ b/ethcore/src/json_tests/chain.rs @@ -15,16 +15,14 @@ // along with Parity. If not, see . use std::sync::Arc; -use client::{BlockChainClient, Client, ClientConfig}; +use client::{EvmTestClient, BlockChainClient, Client, ClientConfig}; use block::Block; -use ethereum; -use tests::helpers::*; use spec::Genesis; use ethjson; use miner::Miner; use io::IoChannel; -pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { +pub fn json_chain_test(json_data: &[u8]) -> Vec { ::ethcore_logger::init_log(); let tests = ethjson::blockchain::Test::load(json_data).unwrap(); let mut failed = Vec::new(); @@ -42,15 +40,16 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { flush!(" - {}...", name); let spec = { + let mut spec = match EvmTestClient::spec_from_json(&blockchain.network) { + Some(spec) => (*spec).clone(), + None => { + println!(" - {} | {:?} Ignoring tests because of missing spec", name, blockchain.network); + continue; + } + }; + let genesis = Genesis::from(blockchain.genesis()); let state = From::from(blockchain.pre_state.clone()); - let mut spec = match era { - ChainEra::Frontier => ethereum::new_frontier_test(), - ChainEra::Homestead => ethereum::new_homestead_test(), - ChainEra::Eip150 => ethereum::new_eip150_test(), - ChainEra::_Eip161 => ethereum::new_eip161_test(), - ChainEra::TransitionTest => ethereum::new_transition_test(), - }; spec.set_genesis_state(state).expect("Failed to overwrite genesis state"); spec.overwrite_genesis_params(genesis); assert!(spec.is_state_root_valid()); @@ -86,67 +85,69 @@ pub fn json_chain_test(json_data: &[u8], era: ChainEra) -> Vec { failed } -mod frontier_era_tests { - use tests::helpers::*; +mod block_tests { use super::json_chain_test; fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::Frontier) + json_chain_test(json_data) } declare_test!{BlockchainTests_bcBlockGasLimitTest, "BlockchainTests/bcBlockGasLimitTest"} - declare_test!{BlockchainTests_bcForkBlockTest, "BlockchainTests/bcForkBlockTest"} + declare_test!{BlockchainTests_bcExploitTest, "BlockchainTests/bcExploitTest"} + declare_test!{BlockchainTests_bcForgedTest, "BlockchainTests/bcForgedTest"} declare_test!{BlockchainTests_bcForkStressTest, "BlockchainTests/bcForkStressTest"} - declare_test!{BlockchainTests_bcForkUncle, "BlockchainTests/bcForkUncle"} declare_test!{BlockchainTests_bcGasPricerTest, "BlockchainTests/bcGasPricerTest"} declare_test!{BlockchainTests_bcInvalidHeaderTest, "BlockchainTests/bcInvalidHeaderTest"} - // TODO [ToDr] Ignored because of incorrect JSON (https://github.com/ethereum/tests/pull/113) - declare_test!{ignore => BlockchainTests_bcInvalidRLPTest, "BlockchainTests/bcInvalidRLPTest"} declare_test!{BlockchainTests_bcMultiChainTest, "BlockchainTests/bcMultiChainTest"} - declare_test!{BlockchainTests_bcRPC_API_Test, "BlockchainTests/bcRPC_API_Test"} - declare_test!{BlockchainTests_bcStateTest, "BlockchainTests/bcStateTest"} + declare_test!{BlockchainTests_bcRandomBlockhashTest, "BlockchainTests/bcRandomBlockhashTest"} declare_test!{BlockchainTests_bcTotalDifficultyTest, "BlockchainTests/bcTotalDifficultyTest"} declare_test!{BlockchainTests_bcUncleHeaderValiditiy, "BlockchainTests/bcUncleHeaderValiditiy"} declare_test!{BlockchainTests_bcUncleTest, "BlockchainTests/bcUncleTest"} declare_test!{BlockchainTests_bcValidBlockTest, "BlockchainTests/bcValidBlockTest"} declare_test!{BlockchainTests_bcWalletTest, "BlockchainTests/bcWalletTest"} - declare_test!{BlockchainTests_RandomTests_bl10251623GO, "BlockchainTests/RandomTests/bl10251623GO"} - declare_test!{BlockchainTests_RandomTests_bl201507071825GO, "BlockchainTests/RandomTests/bl201507071825GO"} + declare_test!{BlockchainTests_GeneralStateTest_stAttackTest, "BlockchainTests/GeneralStateTests/stAttackTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stBadOpcodeTest, "BlockchainTests/GeneralStateTests/stBadOpcode/"} + declare_test!{BlockchainTests_GeneralStateTest_stCallCodes, "BlockchainTests/GeneralStateTests/stCallCodes/"} + declare_test!{BlockchainTests_GeneralStateTest_stCallDelegateCodesCallCodeHomestead, "BlockchainTests/GeneralStateTests/stCallDelegateCodesCallCodeHomestead/"} + declare_test!{BlockchainTests_GeneralStateTest_stCallDelegateCodesHomestead, "BlockchainTests/GeneralStateTests/stCallDelegateCodesHomestead/"} + declare_test!{BlockchainTests_GeneralStateTest_stChangedEIP150, "BlockchainTests/GeneralStateTests/stChangedEIP150/"} + declare_test!{BlockchainTests_GeneralStateTest_stCodeSizeLimit, "BlockchainTests/GeneralStateTests/stCodeSizeLimit/"} + declare_test!{BlockchainTests_GeneralStateTest_stCreateTest, "BlockchainTests/GeneralStateTests/stCreateTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stDelegatecallTestHomestead, "BlockchainTests/GeneralStateTests/stDelegatecallTestHomestead/"} + declare_test!{BlockchainTests_GeneralStateTest_stEIP150singleCodeGasPrices, "BlockchainTests/GeneralStateTests/stEIP150singleCodeGasPrices/"} + declare_test!{BlockchainTests_GeneralStateTest_stEIP150Specific, "BlockchainTests/GeneralStateTests/stEIP150Specific/"} + declare_test!{BlockchainTests_GeneralStateTest_stEIP158Specific, "BlockchainTests/GeneralStateTests/stEIP158Specific/"} + declare_test!{BlockchainTests_GeneralStateTest_stExample, "BlockchainTests/GeneralStateTests/stExample/"} + declare_test!{BlockchainTests_GeneralStateTest_stHomesteadSpecific, "BlockchainTests/GeneralStateTests/stHomesteadSpecific/"} + declare_test!{BlockchainTests_GeneralStateTest_stInitCodeTest, "BlockchainTests/GeneralStateTests/stInitCodeTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stLogTests, "BlockchainTests/GeneralStateTests/stLogTests/"} + declare_test!{BlockchainTests_GeneralStateTest_stMemExpandingEIP150Calls, "BlockchainTests/GeneralStateTests/stMemExpandingEIP150Calls/"} + declare_test!{heavy => BlockchainTests_GeneralStateTest_stMemoryStressTest, "BlockchainTests/GeneralStateTests/stMemoryStressTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stMemoryTest, "BlockchainTests/GeneralStateTests/stMemoryTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stNonZeroCallsTest, "BlockchainTests/GeneralStateTests/stNonZeroCallsTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stPreCompiledContracts, "BlockchainTests/GeneralStateTests/stPreCompiledContracts/"} + declare_test!{heavy => BlockchainTests_GeneralStateTest_stQuadraticComplexityTest, "BlockchainTests/GeneralStateTests/stQuadraticComplexityTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stRandom, "BlockchainTests/GeneralStateTests/stRandom/"} + declare_test!{BlockchainTests_GeneralStateTest_stRecursiveCreate, "BlockchainTests/GeneralStateTests/stRecursiveCreate/"} + declare_test!{BlockchainTests_GeneralStateTest_stRefundTest, "BlockchainTests/GeneralStateTests/stRefundTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stReturnDataTest, "BlockchainTests/GeneralStateTests/stReturnDataTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stRevertTest, "BlockchainTests/GeneralStateTests/stRevertTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stSolidityTest, "BlockchainTests/GeneralStateTests/stSolidityTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stSpecialTest, "BlockchainTests/GeneralStateTests/stSpecialTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stStackTests, "BlockchainTests/GeneralStateTests/stStackTests/"} + declare_test!{BlockchainTests_GeneralStateTest_stStaticCall, "BlockchainTests/GeneralStateTests/stStaticCall/"} + declare_test!{BlockchainTests_GeneralStateTest_stSystemOperationsTest, "BlockchainTests/GeneralStateTests/stSystemOperationsTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stTransactionTest, "BlockchainTests/GeneralStateTests/stTransactionTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stTransitionTest, "BlockchainTests/GeneralStateTests/stTransitionTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stWalletTest, "BlockchainTests/GeneralStateTests/stWalletTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stZeroCallsRevert, "BlockchainTests/GeneralStateTests/stZeroCallsRevert/"} + declare_test!{BlockchainTests_GeneralStateTest_stZeroCallsTest, "BlockchainTests/GeneralStateTests/stZeroCallsTest/"} + declare_test!{BlockchainTests_GeneralStateTest_stZeroKnowledge, "BlockchainTests/GeneralStateTests/stZeroKnowledge/"} + + declare_test!{BlockchainTests_TransitionTests_bcEIP158ToByzantium, "BlockchainTests/TransitionTests/bcEIP158ToByzantium/"} + declare_test!{BlockchainTests_TransitionTests_bcFrontierToHomestead, "BlockchainTests/TransitionTests/bcFrontierToHomestead/"} + declare_test!{BlockchainTests_TransitionTests_bcHomesteadToDao, "BlockchainTests/TransitionTests/bcHomesteadToDao/"} + declare_test!{BlockchainTests_TransitionTests_bcHomesteadToEIP150, "BlockchainTests/TransitionTests/bcHomesteadToEIP150/"} } -mod transition_tests { - use tests::helpers::*; - use super::json_chain_test; - - fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::TransitionTest) - } - - declare_test!{BlockchainTests_TestNetwork_bcSimpleTransitionTest, "BlockchainTests/TestNetwork/bcSimpleTransitionTest"} - declare_test!{BlockchainTests_TestNetwork_bcTheDaoTest, "BlockchainTests/TestNetwork/bcTheDaoTest"} - declare_test!{BlockchainTests_TestNetwork_bcEIP150Test, "BlockchainTests/TestNetwork/bcEIP150Test"} -} - -mod eip150_blockchain_tests { - use tests::helpers::*; - use super::json_chain_test; - - fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::Eip150) - } - - declare_test!{BlockchainTests_EIP150_bcBlockGasLimitTest, "BlockchainTests/EIP150/bcBlockGasLimitTest"} - declare_test!{BlockchainTests_EIP150_bcForkStressTest, "BlockchainTests/EIP150/bcForkStressTest"} - declare_test!{BlockchainTests_EIP150_bcGasPricerTest, "BlockchainTests/EIP150/bcGasPricerTest"} - declare_test!{BlockchainTests_EIP150_bcInvalidHeaderTest, "BlockchainTests/EIP150/bcInvalidHeaderTest"} - declare_test!{BlockchainTests_EIP150_bcInvalidRLPTest, "BlockchainTests/EIP150/bcInvalidRLPTest"} - declare_test!{BlockchainTests_EIP150_bcMultiChainTest, "BlockchainTests/EIP150/bcMultiChainTest"} - declare_test!{BlockchainTests_EIP150_bcRPC_API_Test, "BlockchainTests/EIP150/bcRPC_API_Test"} - declare_test!{BlockchainTests_EIP150_bcStateTest, "BlockchainTests/EIP150/bcStateTest"} - declare_test!{BlockchainTests_EIP150_bcTotalDifficultyTest, "BlockchainTests/EIP150/bcTotalDifficultyTest"} - declare_test!{BlockchainTests_EIP150_bcUncleHeaderValiditiy, "BlockchainTests/EIP150/bcUncleHeaderValiditiy"} - declare_test!{BlockchainTests_EIP150_bcUncleTest, "BlockchainTests/EIP150/bcUncleTest"} - declare_test!{BlockchainTests_EIP150_bcValidBlockTest, "BlockchainTests/EIP150/bcValidBlockTest"} - declare_test!{BlockchainTests_EIP150_bcWalletTest, "BlockchainTests/EIP150/bcWalletTest"} -} diff --git a/ethcore/src/json_tests/executive.rs b/ethcore/src/json_tests/executive.rs index f6d3023c9..3a28a4825 100644 --- a/ethcore/src/json_tests/executive.rs +++ b/ethcore/src/json_tests/executive.rs @@ -32,6 +32,8 @@ use trace::{Tracer, NoopTracer}; use trace::{VMTracer, NoopVMTracer}; use bytes::{Bytes, BytesRef}; use trie; +use rlp::RlpStream; +use hash::keccak; #[derive(Debug, PartialEq, Clone)] struct CallCreate { @@ -162,8 +164,8 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for TestExt<'a, T, V, B, E> self.ext.log(topics, data) } - fn ret(self, gas: &U256, data: &ReturnData) -> Result { - self.ext.ret(gas, data) + fn ret(self, gas: &U256, data: &ReturnData, apply_state: bool) -> Result { + self.ext.ret(gas, data, apply_state) } fn suicide(&mut self, refund_address: &Address) -> vm::Result<()> { @@ -182,6 +184,10 @@ impl<'a, T: 'a, V: 'a, B: 'a, E: 'a> Ext for TestExt<'a, T, V, B, E> 0 } + fn is_static(&self) -> bool { + false + } + fn inc_sstore_clears(&mut self) { self.ext.inc_sstore_clears() } @@ -255,6 +261,14 @@ fn do_json_test_for(vm_type: &VMType, json_data: &[u8]) -> Vec { (res.finalize(ex), callcreates) }; + let log_hash = { + let mut rlp = RlpStream::new_list(substate.logs.len()); + for l in &substate.logs { + rlp.append(l); + } + keccak(&rlp.drain()) + }; + match res { Err(_) => fail_unless(out_of_gas, "didn't expect to run out of gas."), Ok(res) => { @@ -262,6 +276,7 @@ fn do_json_test_for(vm_type: &VMType, json_data: &[u8]) -> Vec { fail_unless(Some(res.gas_left) == vm.gas_left.map(Into::into), "gas_left is incorrect"); let vm_output: Option> = vm.output.map(Into::into); fail_unless(Some(output) == vm_output, "output is incorrect"); + fail_unless(Some(log_hash) == vm.logs.map(|h| h.0), "logs are incorrect"); for (address, account) in vm.post_state.unwrap().into_iter() { let address = address.into(); @@ -295,15 +310,15 @@ fn do_json_test_for(vm_type: &VMType, json_data: &[u8]) -> Vec { } declare_test!{ExecutiveTests_vmArithmeticTest, "VMTests/vmArithmeticTest"} -declare_test!{ExecutiveTests_vmBitwiseLogicOperationTest, "VMTests/vmBitwiseLogicOperationTest"} +declare_test!{ExecutiveTests_vmBitwiseLogicOperationTest, "VMTests/vmBitwiseLogicOperation"} declare_test!{ExecutiveTests_vmBlockInfoTest, "VMTests/vmBlockInfoTest"} // TODO [todr] Fails with Signal 11 when using JIT -declare_test!{ExecutiveTests_vmEnvironmentalInfoTest, "VMTests/vmEnvironmentalInfoTest"} -declare_test!{ExecutiveTests_vmIOandFlowOperationsTest, "VMTests/vmIOandFlowOperationsTest"} -declare_test!{heavy => ExecutiveTests_vmInputLimits, "VMTests/vmInputLimits"} +declare_test!{ExecutiveTests_vmEnvironmentalInfoTest, "VMTests/vmEnvironmentalInfo"} +declare_test!{ExecutiveTests_vmIOandFlowOperationsTest, "VMTests/vmIOandFlowOperations"} declare_test!{ExecutiveTests_vmLogTest, "VMTests/vmLogTest"} -declare_test!{ExecutiveTests_vmPerformanceTest, "VMTests/vmPerformanceTest"} +declare_test!{heavy => ExecutiveTests_vmPerformance, "VMTests/vmPerformance"} declare_test!{ExecutiveTests_vmPushDupSwapTest, "VMTests/vmPushDupSwapTest"} +declare_test!{ExecutiveTests_vmRandomTest, "VMTests/vmRandomTest"} declare_test!{ExecutiveTests_vmSha3Test, "VMTests/vmSha3Test"} -declare_test!{ExecutiveTests_vmSystemOperationsTest, "VMTests/vmSystemOperationsTest"} -declare_test!{ExecutiveTests_vmtests, "VMTests/vmtests"} +declare_test!{ExecutiveTests_vmSystemOperationsTest, "VMTests/vmSystemOperations"} +declare_test!{ExecutiveTests_vmTests, "VMTests/vmTests"} diff --git a/ethcore/src/json_tests/homestead_chain.rs b/ethcore/src/json_tests/homestead_chain.rs deleted file mode 100644 index 5f0fe5769..000000000 --- a/ethcore/src/json_tests/homestead_chain.rs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2015-2017 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -use super::chain::json_chain_test; -use tests::helpers::*; - -fn do_json_test(json_data: &[u8]) -> Vec { - json_chain_test(json_data, ChainEra::Homestead) -} - -declare_test!{BlockchainTests_Homestead_bcBlockGasLimitTest, "BlockchainTests/Homestead/bcBlockGasLimitTest"} -declare_test!{BlockchainTests_Homestead_bcForkStressTest, "BlockchainTests/Homestead/bcForkStressTest"} -declare_test!{BlockchainTests_Homestead_bcGasPricerTest, "BlockchainTests/Homestead/bcGasPricerTest"} -declare_test!{BlockchainTests_Homestead_bcInvalidHeaderTest, "BlockchainTests/Homestead/bcInvalidHeaderTest"} -declare_test!{BlockchainTests_Homestead_bcInvalidRLPTest, "BlockchainTests/Homestead/bcInvalidRLPTest"} -declare_test!{BlockchainTests_Homestead_bcMultiChainTest, "BlockchainTests/Homestead/bcMultiChainTest"} -declare_test!{BlockchainTests_Homestead_bcRPC_API_Test, "BlockchainTests/Homestead/bcRPC_API_Test"} -declare_test!{BlockchainTests_Homestead_bcStateTest, "BlockchainTests/Homestead/bcStateTest"} -declare_test!{BlockchainTests_Homestead_bcTotalDifficultyTest, "BlockchainTests/Homestead/bcTotalDifficultyTest"} -declare_test!{BlockchainTests_Homestead_bcUncleHeaderValiditiy, "BlockchainTests/Homestead/bcUncleHeaderValiditiy"} -declare_test!{BlockchainTests_Homestead_bcUncleTest, "BlockchainTests/Homestead/bcUncleTest"} -declare_test!{BlockchainTests_Homestead_bcValidBlockTest, "BlockchainTests/Homestead/bcValidBlockTest"} -declare_test!{BlockchainTests_Homestead_bcWalletTest, "BlockchainTests/Homestead/bcWalletTest"} -declare_test!{BlockchainTests_Homestead_bcShanghaiLove, "BlockchainTests/Homestead/bcShanghaiLove"} -declare_test!{BlockchainTests_Homestead_bcSuicideIssue, "BlockchainTests/Homestead/bcSuicideIssue"} -declare_test!{BlockchainTests_Homestead_bcExploitTest, "BlockchainTests/Homestead/bcExploitTest"} diff --git a/ethcore/src/json_tests/mod.rs b/ethcore/src/json_tests/mod.rs index 406782072..ab3205d18 100644 --- a/ethcore/src/json_tests/mod.rs +++ b/ethcore/src/json_tests/mod.rs @@ -21,5 +21,4 @@ mod transaction; mod executive; mod state; mod chain; -mod homestead_chain; mod trie; diff --git a/ethcore/src/json_tests/state.rs b/ethcore/src/json_tests/state.rs index 51961a2bb..cc6b0ed1d 100644 --- a/ethcore/src/json_tests/state.rs +++ b/ethcore/src/json_tests/state.rs @@ -97,9 +97,8 @@ mod state_tests { } declare_test!{GeneralStateTest_stAttackTest, "GeneralStateTests/stAttackTest/"} - declare_test!{GeneralStateTest_stBoundsTest, "GeneralStateTests/stBoundsTest/"} + declare_test!{GeneralStateTest_stBadOpcodeTest, "GeneralStateTests/stBadOpcode/"} declare_test!{GeneralStateTest_stCallCodes, "GeneralStateTests/stCallCodes/"} - declare_test!{skip => [ "createJS_ExampleContract" ], GeneralStateTest_stCallCreateCallCodeTest, "GeneralStateTests/stCallCreateCallCodeTest/"} declare_test!{GeneralStateTest_stCallDelegateCodesCallCodeHomestead, "GeneralStateTests/stCallDelegateCodesCallCodeHomestead/"} declare_test!{GeneralStateTest_stCallDelegateCodesHomestead, "GeneralStateTests/stCallDelegateCodesHomestead/"} declare_test!{GeneralStateTest_stChangedEIP150, "GeneralStateTests/stChangedEIP150/"} @@ -108,6 +107,7 @@ mod state_tests { declare_test!{GeneralStateTest_stDelegatecallTestHomestead, "GeneralStateTests/stDelegatecallTestHomestead/"} declare_test!{GeneralStateTest_stEIP150singleCodeGasPrices, "GeneralStateTests/stEIP150singleCodeGasPrices/"} declare_test!{GeneralStateTest_stEIP150Specific, "GeneralStateTests/stEIP150Specific/"} + declare_test!{GeneralStateTest_stEIP158Specific, "GeneralStateTests/stEIP158Specific/"} declare_test!{GeneralStateTest_stExample, "GeneralStateTests/stExample/"} declare_test!{GeneralStateTest_stHomesteadSpecific, "GeneralStateTests/stHomesteadSpecific/"} declare_test!{GeneralStateTest_stInitCodeTest, "GeneralStateTests/stInitCodeTest/"} @@ -121,15 +121,18 @@ mod state_tests { declare_test!{GeneralStateTest_stRandom, "GeneralStateTests/stRandom/"} declare_test!{GeneralStateTest_stRecursiveCreate, "GeneralStateTests/stRecursiveCreate/"} declare_test!{GeneralStateTest_stRefundTest, "GeneralStateTests/stRefundTest/"} - declare_test!{skip => [ "RevertDepthCreateAddressCollision" ], GeneralStateTest_stRevertTest, "GeneralStateTests/stRevertTest/"} + declare_test!{GeneralStateTest_stReturnDataTest, "GeneralStateTests/stReturnDataTest/"} + declare_test!{GeneralStateTest_stRevertTest, "GeneralStateTests/stRevertTest/"} declare_test!{GeneralStateTest_stSolidityTest, "GeneralStateTests/stSolidityTest/"} declare_test!{GeneralStateTest_stSpecialTest, "GeneralStateTests/stSpecialTest/"} declare_test!{GeneralStateTest_stStackTests, "GeneralStateTests/stStackTests/"} + declare_test!{GeneralStateTest_stStaticCall, "GeneralStateTests/stStaticCall/"} declare_test!{GeneralStateTest_stSystemOperationsTest, "GeneralStateTests/stSystemOperationsTest/"} declare_test!{GeneralStateTest_stTransactionTest, "GeneralStateTests/stTransactionTest/"} declare_test!{GeneralStateTest_stTransitionTest, "GeneralStateTests/stTransitionTest/"} declare_test!{GeneralStateTest_stWalletTest, "GeneralStateTests/stWalletTest/"} declare_test!{GeneralStateTest_stZeroCallsRevert, "GeneralStateTests/stZeroCallsRevert/"} declare_test!{GeneralStateTest_stZeroCallsTest, "GeneralStateTests/stZeroCallsTest/"} + declare_test!{GeneralStateTest_stZeroKnowledge, "GeneralStateTests/stZeroKnowledge/"} } diff --git a/ethcore/src/json_tests/transaction.rs b/ethcore/src/json_tests/transaction.rs index 3d71a5faf..6ae8123f1 100644 --- a/ethcore/src/json_tests/transaction.rs +++ b/ethcore/src/json_tests/transaction.rs @@ -25,7 +25,7 @@ fn do_json_test(json_data: &[u8]) -> Vec { let mut failed = Vec::new(); let frontier_schedule = evm::Schedule::new_frontier(); let homestead_schedule = evm::Schedule::new_homestead(); - let metropolis_schedule = evm::Schedule::new_metropolis(); + let byzantium_schedule = evm::Schedule::new_byzantium(); for (name, test) in tests.into_iter() { let mut fail_unless = |cond: bool, title: &str| if !cond { failed.push(name.clone()); println!("Transaction failed: {:?}: {:?}", name, title); }; @@ -34,7 +34,7 @@ fn do_json_test(json_data: &[u8]) -> Vec { None => &frontier_schedule, Some(x) if x < 1_150_000 => &frontier_schedule, Some(x) if x < 3_000_000 => &homestead_schedule, - Some(_) => &metropolis_schedule + Some(_) => &byzantium_schedule }; let allow_chain_id_of_one = number.map_or(false, |n| n >= 2_675_000); let allow_unsigned = number.map_or(false, |n| n >= 3_000_000); @@ -75,18 +75,13 @@ fn do_json_test(json_data: &[u8]) -> Vec { failed } -declare_test!{TransactionTests_ttTransactionTest, "TransactionTests/ttTransactionTest"} -declare_test!{heavy => TransactionTests_tt10mbDataField, "TransactionTests/tt10mbDataField"} -declare_test!{TransactionTests_ttWrongRLPTransaction, "TransactionTests/ttWrongRLPTransaction"} -declare_test!{TransactionTests_Homestead_ttTransactionTest, "TransactionTests/Homestead/ttTransactionTest"} -declare_test!{heavy => TransactionTests_Homestead_tt10mbDataField, "TransactionTests/Homestead/tt10mbDataField"} -declare_test!{TransactionTests_Homestead_ttWrongRLPTransaction, "TransactionTests/Homestead/ttWrongRLPTransaction"} -declare_test!{TransactionTests_RandomTests_tr201506052141PYTHON, "TransactionTests/RandomTests/tr201506052141PYTHON"} -declare_test!{TransactionTests_Homestead_ttTransactionTestEip155VitaliksTests, "TransactionTests/Homestead/ttTransactionTestEip155VitaliksTests"} -declare_test!{TransactionTests_EIP155_ttTransactionTest, "TransactionTests/EIP155/ttTransactionTest"} -declare_test!{TransactionTests_EIP155_ttTransactionTestEip155VitaliksTests, "TransactionTests/EIP155/ttTransactionTestEip155VitaliksTests"} -declare_test!{TransactionTests_EIP155_ttTransactionTestVRule, "TransactionTests/EIP155/ttTransactionTestVRule"} - -declare_test!{TransactionTests_Metropolis_ttMetropolisTest, "TransactionTests/Metropolis/ttMetropolisTest"} -declare_test!{TransactionTests_Metropolis_ttTransactionTest, "TransactionTests/Metropolis/ttTransactionTest"} -declare_test!{TransactionTests_Metropolis_ttTransactionTestZeroSig, "TransactionTests/Metropolis/ttTransactionTestZeroSig"} +declare_test!{TransactionTests_ttEip155VitaliksHomesead, "TransactionTests/ttEip155VitaliksHomesead"} +declare_test!{TransactionTests_ttEip155VitaliksEip158, "TransactionTests/ttEip155VitaliksEip158"} +declare_test!{TransactionTests_ttEip158, "TransactionTests/ttEip158"} +declare_test!{TransactionTests_ttFrontier, "TransactionTests/ttFrontier"} +declare_test!{TransactionTests_ttHomestead, "TransactionTests/ttHomestead"} +declare_test!{TransactionTests_ttVRuleEip158, "TransactionTests/ttVRuleEip158"} +declare_test!{TransactionTests_ttWrongRLPFrontier, "TransactionTests/ttWrongRLPFrontier"} +declare_test!{TransactionTests_ttWrongRLPHomestead, "TransactionTests/ttWrongRLPHomestead"} +declare_test!{TransactionTests_ttConstantinople, "TransactionTests/ttConstantinople"} +declare_test!{TransactionTests_ttSpecConstantinople, "TransactionTests/ttSpecConstantinople"} diff --git a/ethcore/src/spec/spec.rs b/ethcore/src/spec/spec.rs index 0cf5e7eb5..f4f961cc0 100644 --- a/ethcore/src/spec/spec.rs +++ b/ethcore/src/spec/spec.rs @@ -70,6 +70,8 @@ pub struct CommonParams { pub fork_block: Option<(BlockNumber, H256)>, /// Number of first block where EIP-98 rules begin. pub eip98_transition: BlockNumber, + /// Number of first block where EIP-658 rules begin. + pub eip658_transition: BlockNumber, /// Number of first block where EIP-155 rules begin. pub eip155_transition: BlockNumber, /// Validate block receipts root. @@ -125,7 +127,7 @@ impl CommonParams { schedule.have_static_call = block_number >= self.eip214_transition; schedule.have_return_data = block_number >= self.eip211_transition; if block_number >= self.eip210_transition { - schedule.blockhash_gas = 350; + schedule.blockhash_gas = 800; } if block_number >= self.dust_protection_transition { schedule.kill_dust = match self.remove_dust_contracts { @@ -172,6 +174,7 @@ impl From for CommonParams { eip210_contract_gas: p.eip210_contract_gas.map_or(1000000.into(), Into::into), eip211_transition: p.eip211_transition.map_or(BlockNumber::max_value(), Into::into), eip214_transition: p.eip214_transition.map_or(BlockNumber::max_value(), Into::into), + eip658_transition: p.eip658_transition.map_or(BlockNumber::max_value(), Into::into), dust_protection_transition: p.dust_protection_transition.map_or(BlockNumber::max_value(), Into::into), nonce_cap_increment: p.nonce_cap_increment.map_or(64, Into::into), remove_dust_contracts: p.remove_dust_contracts.unwrap_or(false), @@ -229,7 +232,33 @@ pub struct Spec { genesis_state: PodState, } -fn load_from>(cache_dir: T, s: ethjson::spec::Spec) -> Result { +#[cfg(test)] +impl Clone for Spec { + fn clone(&self) -> Spec { + Spec { + name: self.name.clone(), + engine: self.engine.clone(), + data_dir: self.data_dir.clone(), + nodes: self.nodes.clone(), + parent_hash: self.parent_hash.clone(), + transactions_root: self.transactions_root.clone(), + receipts_root: self.receipts_root.clone(), + author: self.author.clone(), + difficulty: self.difficulty.clone(), + gas_limit: self.gas_limit.clone(), + gas_used: self.gas_used.clone(), + timestamp: self.timestamp.clone(), + extra_data: self.extra_data.clone(), + seal_rlp: self.seal_rlp.clone(), + constructors: self.constructors.clone(), + state_root_memo: RwLock::new(*self.state_root_memo.read()), + genesis_state: self.genesis_state.clone(), + } + } +} + +/// Load from JSON object. +pub fn load_from>(cache_dir: T, s: ethjson::spec::Spec) -> Result { let builtins = s.accounts.builtins().into_iter().map(|p| (p.0.into(), From::from(p.1))).collect(); let g = Genesis::from(s.genesis); let GenericSeal(seal_rlp) = g.seal.into(); diff --git a/ethcore/src/state/mod.rs b/ethcore/src/state/mod.rs index 8f7259c4b..3935d7d86 100644 --- a/ethcore/src/state/mod.rs +++ b/ethcore/src/state/mod.rs @@ -503,9 +503,10 @@ impl State { self.ensure_cached(a, RequireCache::None, false, |a| a.map_or(false, |a| !a.is_null())) } - /// Determine whether an account exists and has code. - pub fn exists_and_has_code(&self, a: &Address) -> trie::Result { - self.ensure_cached(a, RequireCache::CodeSize, false, |a| a.map_or(false, |a| a.code_size().map_or(false, |size| size != 0))) + /// Determine whether an account exists and has code or non-zero nonce. + pub fn exists_and_has_code_or_nonce(&self, a: &Address) -> trie::Result { + self.ensure_cached(a, RequireCache::CodeSize, false, + |a| a.map_or(false, |a| a.code_hash() != KECCAK_EMPTY || *a.nonce() != self.account_start_nonce)) } /// Get the balance of account `a`. @@ -697,15 +698,26 @@ impl State { let options = TransactOptions::new(tracer, vm_tracer); let e = self.execute(env_info, engine, t, options, false)?; - let state_root = if env_info.number < engine.params().eip98_transition || env_info.number < engine.params().validate_receipts_transition { + let eip658 = env_info.number >= engine.params().eip658_transition; + let no_intermediate_commits = + eip658 || + (env_info.number >= engine.params().eip98_transition && env_info.number >= engine.params().validate_receipts_transition); + + let state_root = if no_intermediate_commits { + None + } else { self.commit()?; Some(self.root().clone()) + }; + + let status_byte = if eip658 { + Some(if e.exception.is_some() { 0 } else { 1 }) } else { None }; let output = e.output; - let receipt = Receipt::new(state_root, e.cumulative_gas_used, e.logs); + let receipt = Receipt::new(state_root, status_byte, e.cumulative_gas_used, e.logs); trace!(target: "state", "Transaction receipt: {:?}", receipt); Ok(ApplyOutcome { diff --git a/ethcore/src/tests/evm.rs b/ethcore/src/tests/evm.rs index f8eb178d5..24f1e2acb 100644 --- a/ethcore/src/tests/evm.rs +++ b/ethcore/src/tests/evm.rs @@ -24,7 +24,7 @@ fn test_blockhash_eip210(factory: Factory) { let test_blockhash_contract = "73fffffffffffffffffffffffffffffffffffffffe33141561007a57600143036020526000356101006020510755600061010060205107141561005057600035610100610100602051050761010001555b6000620100006020510714156100755760003561010062010000602051050761020001555b61014a565b4360003512151561009057600060405260206040f35b610100600035430312156100b357610100600035075460605260206060f3610149565b62010000600035430312156100d157600061010060003507146100d4565b60005b156100f6576101006101006000350507610100015460805260206080f3610148565b630100000060003543031215610116576000620100006000350714610119565b60005b1561013c57610100620100006000350507610200015460a052602060a0f3610147565b600060c052602060c0f35b5b5b5b5b"; let blockhash_contract_code = Arc::new(test_blockhash_contract.from_hex().unwrap()); let blockhash_contract_code_hash = keccak(blockhash_contract_code.as_ref()); - let engine = TestEngine::new_metropolis(); + let engine = TestEngine::new_constantinople(); let mut env_info = EnvInfo::default(); // populate state with 256 last hashes diff --git a/ethcore/src/tests/helpers.rs b/ethcore/src/tests/helpers.rs index 80eadcfa5..f61fa9d5a 100644 --- a/ethcore/src/tests/helpers.rs +++ b/ethcore/src/tests/helpers.rs @@ -42,15 +42,6 @@ use transaction::{Action, Transaction, SignedTransaction}; use rlp::{self, RlpStream}; use views::BlockView; -#[cfg(feature = "json-tests")] -pub enum ChainEra { - Frontier, - Homestead, - Eip150, - _Eip161, - TransitionTest, -} - pub struct TestEngine { engine: Arc, max_depth: usize, @@ -64,9 +55,16 @@ impl TestEngine { } } - pub fn new_metropolis() -> TestEngine { + pub fn new_byzantium() -> TestEngine { TestEngine { - engine: ethereum::new_metropolis_test().engine, + engine: ethereum::new_byzantium_test().engine, + max_depth: 0, + } + } + + pub fn new_constantinople() -> TestEngine { + TestEngine { + engine: ethereum::new_constantinople_test().engine, max_depth: 0, } } @@ -427,5 +425,8 @@ pub fn get_default_ethash_params() -> EthashParams { max_gas_limit: U256::max_value(), min_gas_price_transition: u64::max_value(), min_gas_price: U256::zero(), + eip649_transition: u64::max_value(), + eip649_delay: 3_000_000, + eip649_reward: None, } } diff --git a/ethcore/src/trace/types/error.rs b/ethcore/src/trace/types/error.rs index 5cedefd09..70a3c315a 100644 --- a/ethcore/src/trace/types/error.rs +++ b/ethcore/src/trace/types/error.rs @@ -43,6 +43,10 @@ pub enum Error { MutableCallInStaticContext, /// Wasm error Wasm, + /// Contract tried to access past the return data buffer. + OutOfBounds, + /// Execution has been reverted with REVERT instruction. + Reverted, } impl<'a> From<&'a VmError> for Error { @@ -57,6 +61,8 @@ impl<'a> From<&'a VmError> for Error { VmError::Wasm { .. } => Error::Wasm, VmError::Internal(_) => Error::Internal, VmError::MutableCallInStaticContext => Error::MutableCallInStaticContext, + VmError::OutOfBounds => Error::OutOfBounds, + VmError::Reverted => Error::Reverted, } } } @@ -80,6 +86,8 @@ impl fmt::Display for Error { Wasm => "Wasm runtime error", Internal => "Internal error", MutableCallInStaticContext => "Mutable Call In Static Context", + OutOfBounds => "Out of bounds", + Reverted => "Reverted", }; message.fmt(f) } @@ -98,6 +106,8 @@ impl Encodable for Error { BuiltIn => 6, MutableCallInStaticContext => 7, Wasm => 8, + OutOfBounds => 9, + Reverted => 10, }; s.append_internal(&value); @@ -118,6 +128,8 @@ impl Decodable for Error { 6 => Ok(BuiltIn), 7 => Ok(MutableCallInStaticContext), 8 => Ok(Wasm), + 9 => Ok(OutOfBounds), + 10 => Ok(Reverted), _ => Err(DecoderError::Custom("Invalid error type")), } } diff --git a/ethcore/types/src/receipt.rs b/ethcore/types/src/receipt.rs index 759f67050..380a9fa8d 100644 --- a/ethcore/types/src/receipt.rs +++ b/ethcore/types/src/receipt.rs @@ -36,23 +36,29 @@ pub struct Receipt { pub log_bloom: LogBloom, /// The logs stemming from this transaction. pub logs: Vec, + /// Status byte. Optional before EIP-658. + pub status_code: Option, } impl Receipt { /// Create a new receipt. - pub fn new(state_root: Option, gas_used: U256, logs: Vec) -> Receipt { + pub fn new(state_root: Option, status_code: Option, gas_used: U256, logs: Vec) -> Receipt { Receipt { state_root: state_root, gas_used: gas_used, log_bloom: logs.iter().fold(LogBloom::default(), |mut b, l| { b = &b | &l.bloom(); b }), //TODO: use |= operator logs: logs, + status_code: status_code, } } } impl Encodable for Receipt { fn rlp_append(&self, s: &mut RlpStream) { - if let Some(ref root) = self.state_root { + if let Some(ref status) = self.status_code { + s.begin_list(4); + s.append(status); + } else if let Some(ref root) = self.state_root { s.begin_list(4); s.append(root); } else { @@ -69,17 +75,27 @@ impl Decodable for Receipt { if rlp.item_count()? == 3 { Ok(Receipt { state_root: None, + status_code: None, gas_used: rlp.val_at(0)?, log_bloom: rlp.val_at(1)?, logs: rlp.list_at(2)?, }) } else { - Ok(Receipt { - state_root: Some(rlp.val_at(0)?), + let mut receipt = Receipt { gas_used: rlp.val_at(1)?, log_bloom: rlp.val_at(2)?, logs: rlp.list_at(3)?, - }) + state_root: None, + status_code: None, + }; + + let first = rlp.at(0)?; + if first.is_data() && first.data()?.len() == 1 { + receipt.status_code = Some(first.as_val()?); + } else { + receipt.state_root = Some(first.as_val()?); + } + Ok(receipt) } } } @@ -145,6 +161,7 @@ mod tests { fn test_no_state_root() { let expected = ::rustc_hex::FromHex::from_hex("f9014183040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000f838f794dcf421d093428b096ca501a7cd1a740855a7976fc0a00000000000000000000000000000000000000000000000000000000000000000").unwrap(); let r = Receipt::new( + None, None, 0x40cae.into(), vec![LogEntry { @@ -161,6 +178,7 @@ mod tests { let expected = ::rustc_hex::FromHex::from_hex("f90162a02f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee83040caeb9010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000f838f794dcf421d093428b096ca501a7cd1a740855a7976fc0a00000000000000000000000000000000000000000000000000000000000000000").unwrap(); let r = Receipt::new( Some("2f697d671e9ae4ee24a43c4b0d7e15f1cb4ba6de1561120d43b9a4e8c4a8a6ee".into()), + None, 0x40cae.into(), vec![LogEntry { address: "dcf421d093428b096ca501a7cd1a740855a7976f".into(), diff --git a/ethcore/vm/src/error.rs b/ethcore/vm/src/error.rs index 2c2c9a38d..fe8d7054c 100644 --- a/ethcore/vm/src/error.rs +++ b/ethcore/vm/src/error.rs @@ -65,6 +65,10 @@ pub enum Error { Internal(String), /// Wasm runtime error Wasm(String), + /// Out of bounds access in RETURNDATACOPY. + OutOfBounds, + /// Execution has been reverted with REVERT. + Reverted, } @@ -93,6 +97,8 @@ impl fmt::Display for Error { Internal(ref msg) => write!(f, "Internal error: {}", msg), MutableCallInStaticContext => write!(f, "Mutable call in static context"), Wasm(ref msg) => write!(f, "Internal error: {}", msg), + OutOfBounds => write!(f, "Out of bounds"), + Reverted => write!(f, "Reverted"), } } } diff --git a/ethcore/vm/src/ext.rs b/ethcore/vm/src/ext.rs index a4610b672..574af9e82 100644 --- a/ethcore/vm/src/ext.rs +++ b/ethcore/vm/src/ext.rs @@ -34,7 +34,12 @@ pub enum ContractCreateResult { Created(Address, U256), /// Returned when contract creation failed. /// VM doesn't have to know the reason. - Failed + Failed, + /// Returned when contract creation failed. + /// VM doesn't have to know the reason. + FailedInStaticCall, + /// Reverted with REVERT. + Reverted(U256, ReturnData), } /// Result of externalities call function. @@ -44,7 +49,10 @@ pub enum MessageCallResult { Success(U256, ReturnData), /// Returned when message call failed. /// VM doesn't have to know the reason. - Failed + Failed, + /// Returned when message call was reverted. + /// Contains gas left and output data. + Reverted(U256, ReturnData), } /// Specifies how an address is calculated for a new contract. @@ -114,7 +122,7 @@ pub trait Ext { /// Should be called when transaction calls `RETURN` opcode. /// Returns gas_left if cost of returning the data is not too high. - fn ret(self, gas: &U256, data: &ReturnData) -> Result; + fn ret(self, gas: &U256, data: &ReturnData, apply_state: bool) -> Result; /// Should be called when contract commits suicide. /// Address to which funds should be refunded. @@ -143,4 +151,7 @@ pub trait Ext { /// Trace the finalised execution of a single instruction. fn trace_executed(&mut self, _gas_used: U256, _stack_push: &[U256], _mem_diff: Option<(usize, &[u8])>, _store_diff: Option<(U256, U256)>) {} + + /// Check if running in static context. + fn is_static(&self) -> bool; } diff --git a/ethcore/vm/src/schedule.rs b/ethcore/vm/src/schedule.rs index 6966c26e6..04c97b044 100644 --- a/ethcore/vm/src/schedule.rs +++ b/ethcore/vm/src/schedule.rs @@ -111,6 +111,8 @@ pub struct Schedule { pub have_return_data: bool, /// Kill basic accounts below this balance if touched. pub kill_dust: CleanDustMode, + /// Enable EIP-86 rules + pub eip86: bool, } /// Dust accounts cleanup mode. @@ -184,17 +186,17 @@ impl Schedule { blockhash_gas: 20, have_static_call: false, kill_dust: CleanDustMode::Off, + eip86: false, } } - /// Schedule for the Metropolis of the Ethereum main net. - pub fn new_metropolis() -> Schedule { + /// Schedule for the Byzantium fork of the Ethereum main net. + pub fn new_byzantium() -> Schedule { let mut schedule = Self::new_post_eip150(24576, true, true, true); schedule.have_create2 = true; schedule.have_revert = true; schedule.have_static_call = true; schedule.have_return_data = true; - schedule.blockhash_gas = 350; schedule } @@ -246,6 +248,7 @@ impl Schedule { blockhash_gas: 20, have_static_call: false, kill_dust: CleanDustMode::Off, + eip86: false, } } } diff --git a/ethcore/vm/src/tests.rs b/ethcore/vm/src/tests.rs index f56975a9e..40c23f40c 100644 --- a/ethcore/vm/src/tests.rs +++ b/ethcore/vm/src/tests.rs @@ -164,7 +164,7 @@ impl Ext for FakeExt { Ok(()) } - fn ret(self, _gas: &U256, _data: &ReturnData) -> Result { + fn ret(self, _gas: &U256, _data: &ReturnData, _apply_state: bool) -> Result { unimplemented!(); } @@ -185,6 +185,10 @@ impl Ext for FakeExt { self.depth } + fn is_static(&self) -> bool { + false + } + fn inc_sstore_clears(&mut self) { self.sstore_clears += 1; } diff --git a/ethcore/wasm/src/runtime.rs b/ethcore/wasm/src/runtime.rs index 6ddaa7a10..8376d0f39 100644 --- a/ethcore/wasm/src/runtime.rs +++ b/ethcore/wasm/src/runtime.rs @@ -220,7 +220,16 @@ impl<'a, 'b> Runtime<'a, 'b> { vm::ContractCreateResult::Failed => { trace!(target: "wasm", "runtime: create contract fail"); Ok(Some((-1i32).into())) - } + }, + vm::ContractCreateResult::Reverted(gas_left, _) => { + trace!(target: "wasm", "runtime: create contract reverted"); + self.gas_counter = self.gas_limit - gas_left.low_u64(); + Ok(Some((-1i32).into())) + }, + vm::ContractCreateResult::FailedInStaticCall => { + trace!(target: "wasm", "runtime: create contract called in static context"); + Err(interpreter::Error::Trap("CREATE in static context".to_owned())) + }, } } @@ -323,6 +332,11 @@ impl<'a, 'b> Runtime<'a, 'b> { self.memory.set(result_ptr, &result)?; Ok(Some(0i32.into())) }, + vm::MessageCallResult::Reverted(gas_left, _) => { + self.gas_counter = self.gas_limit - gas_left.low_u64(); + self.memory.set(result_ptr, &result)?; + Ok(Some((-1i32).into())) + }, vm::MessageCallResult::Failed => { Ok(Some((-1i32).into())) } diff --git a/evmbin/src/main.rs b/evmbin/src/main.rs index 695349db3..58b4e983b 100644 --- a/evmbin/src/main.rs +++ b/evmbin/src/main.rs @@ -162,7 +162,7 @@ fn run_call(args: Args, mut informant: T) { informant.set_gas(gas); let result = info::run(&spec, gas, None, |mut client| { - client.call(params, &mut informant) + client.call(params, &mut informant).map(|r| (r.gas_left, r.return_data.to_vec())) }); T::finish(result); } diff --git a/json/src/blockchain/blockchain.rs b/json/src/blockchain/blockchain.rs index 07014db07..9edd75313 100644 --- a/json/src/blockchain/blockchain.rs +++ b/json/src/blockchain/blockchain.rs @@ -21,6 +21,7 @@ use hash::H256; use blockchain::state::State; use blockchain::header::Header; use blockchain::block::Block; +use state::test::ForkSpec; use spec::{Genesis, Seal, Ethereum}; /// Blockchain deserialization. @@ -42,7 +43,9 @@ pub struct BlockChain { pub pre_state: State, /// Hash of best block. #[serde(rename="lastblockhash")] - pub best_block: H256 + pub best_block: H256, + /// Network. + pub network: ForkSpec, } impl BlockChain { @@ -102,7 +105,7 @@ mod tests { "rlp" : "0xf90285f90219a0f052d217bd5275a5177a3c3b7debdfe2670f1c8394b2965ccd5c1883cc1a524da01dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347948888f1f195afa192cfee860698584c030f4c9db1a0bac6177a79e910c98d86ec31a09ae37ac2de15b754fd7bed1ba52362c49416bfa0498785da562aa0c5dd5937cf15f22139b0b1bcf3b4fc48986e1bb1dae9292796a0c7778a7376099ee2e5c455791c1885b5c361b95713fddcbe32d97fd01334d296b90100000000000000000010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000008000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000400000000000000000000000000000000000000000000000000000008302000001832fefba82560b8456850c2ca00102030405060708091011121314151617181920212223242526272829303132a05266ca43e81d25925a9ba573c3e4f9180bc076d316d90e63c6f8708b272f5ce28859ba4daed1898e21f866f864800a82c35094095e7baea6a6c7c4c2dfeb977efac326af552d8785012a05f200801ca0ee0b9ec878fbd4258a9473199d8ecc32996a20c323c004e79e0cda20e0418ce3a04e6bc63927d1510bab54f37e46fa036faf4b2c465d271920d9afea1fadf7bd21c0", "transactions" : [ { - "data" : "0x", + "data" : "0x00", "gasLimit" : "0xc350", "gasPrice" : "0x0a", "nonce" : "0x00", @@ -116,6 +119,7 @@ mod tests { "uncleHeaders" : [ ] }], + "network" : "Frontier", "genesisBlockHeader" : { "bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "coinbase" : "8888f1f195afa192cfee860698584c030f4c9db1", diff --git a/json/src/spec/builtin.rs b/json/src/spec/builtin.rs index 892bf532e..34e9a2df1 100644 --- a/json/src/spec/builtin.rs +++ b/json/src/spec/builtin.rs @@ -34,6 +34,15 @@ pub struct Modexp { pub divisor: usize, } +/// Pricing for alt_bn128_pairing. +#[derive(Debug, PartialEq, Deserialize, Clone)] +pub struct AltBn128Pairing { + /// Base price. + pub base: usize, + /// Price per point pair. + pub pair: usize, +} + /// Pricing variants. #[derive(Debug, PartialEq, Deserialize, Clone)] pub enum Pricing { @@ -43,6 +52,9 @@ pub enum Pricing { /// Pricing for modular exponentiation. #[serde(rename="modexp")] Modexp(Modexp), + /// Pricing for alt_bn128_pairing exponentiation. + #[serde(rename="alt_bn128_pairing")] + AltBn128Pairing(AltBn128Pairing), } /// Spec builtin. diff --git a/json/src/spec/ethash.rs b/json/src/spec/ethash.rs index 784a9d477..bfc6fe315 100644 --- a/json/src/spec/ethash.rs +++ b/json/src/spec/ethash.rs @@ -111,6 +111,18 @@ pub struct EthashParams { /// See main EthashParams docs. #[serde(rename="minGasPrice")] pub min_gas_price: Option, + + /// EIP-649 transition block. + #[serde(rename="eip649Transition")] + pub eip649_transition: Option, + + /// EIP-649 bomb delay. + #[serde(rename="eip649Delay")] + pub eip649_delay: Option, + + /// EIP-649 base reward. + #[serde(rename="eip649Reward")] + pub eip649_reward: Option, } /// Ethash engine deserialization. @@ -221,6 +233,9 @@ mod tests { max_gas_limit: None, min_gas_price_transition: None, min_gas_price: None, + eip649_transition: None, + eip649_delay: None, + eip649_reward: None, } }); } @@ -262,6 +277,9 @@ mod tests { max_gas_limit: None, min_gas_price_transition: None, min_gas_price: None, + eip649_transition: None, + eip649_delay: None, + eip649_reward: None, } }); } diff --git a/json/src/spec/params.rs b/json/src/spec/params.rs index 4561bcada..73c9e8d1b 100644 --- a/json/src/spec/params.rs +++ b/json/src/spec/params.rs @@ -85,6 +85,9 @@ pub struct Params { #[serde(rename="eip214Transition")] pub eip214_transition: Option, /// See `CommonParams` docs. + #[serde(rename="eip658Transition")] + pub eip658_transition: Option, + /// See `CommonParams` docs. #[serde(rename="dustProtectionTransition")] pub dust_protection_transition: Option, /// See `CommonParams` docs. diff --git a/json/src/state/test.rs b/json/src/state/test.rs index a63b8ee8d..3a25c007d 100644 --- a/json/src/state/test.rs +++ b/json/src/state/test.rs @@ -104,10 +104,12 @@ pub enum ForkSpec { EIP158, Frontier, Homestead, - // TODO [ToDr] Deprecated - Metropolis, Byzantium, Constantinople, + EIP158ToByzantiumAt5, + FrontierToHomesteadAt5, + HomesteadToDaoAt5, + HomesteadToEIP150At5, } /// State test indexes deserialization. diff --git a/json/src/vm/log.rs b/json/src/vm/log.rs deleted file mode 100644 index c406253bc..000000000 --- a/json/src/vm/log.rs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2015-2017 Parity Technologies (UK) Ltd. -// This file is part of Parity. - -// Parity is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity. If not, see . - -//! Vm log deserialization. - -use hash::{Address, H256, Bloom}; -use bytes::Bytes; - -/// Vm log deserialization. -#[derive(Debug, PartialEq, Deserialize)] -pub struct Log { - /// Log address. - pub address: Address, - /// Log bloom. - pub bloom: Bloom, - /// Data. - pub data: Bytes, - /// Topics. - pub topics: Vec, -} - -#[cfg(test)] -mod tests { - use serde_json; - use vm::Log; - - #[test] - fn log_deserialization() { - let s = r#"{ - "address" : "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6", - "bloom" : "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008800000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000800000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000000", - "data" : "0xaabbffffffffffffffffffffffffffffffffffffffffffffffffffffffffccdd", - "topics" : [ - "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" - ] - }"#; - let _deserialized: Log = serde_json::from_str(s).unwrap(); - // TODO: validate all fields - } -} - diff --git a/json/src/vm/mod.rs b/json/src/vm/mod.rs index 8917d89db..a2588e37c 100644 --- a/json/src/vm/mod.rs +++ b/json/src/vm/mod.rs @@ -19,13 +19,11 @@ pub mod env; pub mod transaction; pub mod vm; -pub mod log; pub mod call; pub mod test; pub use self::env::Env; pub use self::transaction::Transaction; pub use self::vm::Vm; -pub use self::log::Log; pub use self::call::Call; pub use self::test::Test; diff --git a/json/src/vm/vm.rs b/json/src/vm/vm.rs index 36a19cdad..c7e33b609 100644 --- a/json/src/vm/vm.rs +++ b/json/src/vm/vm.rs @@ -18,8 +18,9 @@ use bytes::Bytes; use uint::Uint; +use hash::H256; use blockchain::State; -use vm::{Transaction, Log, Call, Env}; +use vm::{Transaction, Call, Env}; /// Reporesents vm execution environment before and after exeuction of transaction. #[derive(Debug, PartialEq, Deserialize)] @@ -35,8 +36,8 @@ pub struct Vm { /// Gas left after transaction execution. #[serde(rename="gas")] pub gas_left: Option, - /// Logs created during execution of transaction. - pub logs: Option>, + /// Hash of logs created during execution of transaction. + pub logs: Option, /// Transaction output. #[serde(rename="out")] pub output: Option, @@ -83,9 +84,9 @@ mod tests { "value" : "0x0de0b6b3a7640000" }, "gas" : "0x013874", - "logs" : [ - ], + "logs" : "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", "out" : "0x", + "network" : "Frontier", "post" : { "0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6" : { "balance" : "0x0de0b6b3a7640000", diff --git a/rpc/src/v1/tests/eth.rs b/rpc/src/v1/tests/eth.rs index c7a580c58..4563f76e3 100644 --- a/rpc/src/v1/tests/eth.rs +++ b/rpc/src/v1/tests/eth.rs @@ -28,6 +28,7 @@ use ethcore::ethereum; use ethcore::miner::{MinerOptions, Banning, GasPricer, MinerService, ExternalMiner, Miner, PendingSet, PrioritizationStrategy, GasLimit}; use ethcore::account_provider::AccountProvider; use ethjson::blockchain::BlockChain; +use ethjson::state::test::ForkSpec; use io::IoChannel; use bigint::prelude::U256; use bigint::hash::H256; @@ -168,13 +169,13 @@ impl EthTester { #[test] fn harness_works() { - let chain: BlockChain = extract_chain!("BlockchainTests/bcUncleTest"); + let chain: BlockChain = extract_chain!("BlockchainTests/bcWalletTest/wallet2outOf3txs"); let _ = EthTester::from_chain(&chain); } #[test] fn eth_get_balance() { - let chain = extract_chain!("BlockchainTests/bcWalletTest", "wallet2outOf3txs"); + let chain = extract_chain!("BlockchainTests/bcWalletTest/wallet2outOf3txs"); let tester = EthTester::from_chain(&chain); // final account state let req_latest = r#"{ @@ -200,7 +201,7 @@ fn eth_get_balance() { #[test] fn eth_block_number() { - let chain = extract_chain!("BlockchainTests/bcRPC_API_Test"); + let chain = extract_chain!("BlockchainTests/bcGasPricerTest/RPC_API_Test"); let tester = EthTester::from_chain(&chain); let req_number = r#"{ "jsonrpc": "2.0", @@ -215,11 +216,11 @@ fn eth_block_number() { #[test] fn eth_get_block() { - let chain = extract_chain!("BlockchainTests/bcRPC_API_Test"); + let chain = extract_chain!("BlockchainTests/bcGasPricerTest/RPC_API_Test"); let tester = EthTester::from_chain(&chain); let req_block = r#"{"method":"eth_getBlockByNumber","params":["0x0",false],"id":1,"jsonrpc":"2.0"}"#; - let res_block = r#"{"jsonrpc":"2.0","result":{"author":"0x8888f1f195afa192cfee860698584c030f4c9db1","difficulty":"0x20000","extraData":"0x42","gasLimit":"0x2fefd8","gasUsed":"0x0","hash":"0x5a39ed1020c04d4d84539975b893a4e7c53eab6c2965db8bc3468093a31bc5ae","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x8888f1f195afa192cfee860698584c030f4c9db1","mixHash":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","nonce":"0x0102030405060708","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":["0xa056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","0x880102030405060708"],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x1ff","stateRoot":"0x7dba07d6b448a186e9612e5f737d1c909dce473e53199901a302c00646d523c1","timestamp":"0x54c98c81","totalDifficulty":"0x20000","transactions":[],"transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","uncles":[]},"id":1}"#.to_owned(); + let res_block = r#"{"jsonrpc":"2.0","result":{"author":"0x8888f1f195afa192cfee860698584c030f4c9db1","difficulty":"0x20000","extraData":"0x42","gasLimit":"0x1df5d44","gasUsed":"0x0","hash":"0xcded1bc807465a72e2d54697076ab858f28b15d4beaae8faa47339c8eee386a3","logsBloom":"0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000","miner":"0x8888f1f195afa192cfee860698584c030f4c9db1","mixHash":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","nonce":"0x0102030405060708","number":"0x0","parentHash":"0x0000000000000000000000000000000000000000000000000000000000000000","receiptsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","sealFields":["0xa056e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","0x880102030405060708"],"sha3Uncles":"0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347","size":"0x200","stateRoot":"0x7dba07d6b448a186e9612e5f737d1c909dce473e53199901a302c00646d523c1","timestamp":"0x54c98c81","totalDifficulty":"0x20000","transactions":[],"transactionsRoot":"0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421","uncles":[]},"id":1}"#; assert_eq!(tester.handler.handle_request_sync(req_block).unwrap(), res_block); } @@ -465,6 +466,6 @@ fn starting_nonce_test() { assert_eq!(r#"{"jsonrpc":"2.0","result":"0x100","id":15}"#, &sample); } -register_test!(eth_transaction_count_1, verify_transaction_counts, "BlockchainTests/bcWalletTest"); -register_test!(eth_transaction_count_2, verify_transaction_counts, "BlockchainTests/bcTotalDifficultyTest"); -register_test!(eth_transaction_count_3, verify_transaction_counts, "BlockchainTests/bcGasPricerTest"); +register_test!(eth_transaction_count_1, verify_transaction_counts, "BlockchainTests/bcWalletTest/wallet2outOf3txs"); +register_test!(eth_transaction_count_2, verify_transaction_counts, "BlockchainTests/bcTotalDifficultyTest/sideChainWithMoreTransactions"); +register_test!(eth_transaction_count_3, verify_transaction_counts, "BlockchainTests/bcGasPricerTest/RPC_API_Test"); diff --git a/rpc/src/v1/tests/mod.rs b/rpc/src/v1/tests/mod.rs index a48727475..31ac1c541 100644 --- a/rpc/src/v1/tests/mod.rs +++ b/rpc/src/v1/tests/mod.rs @@ -19,19 +19,8 @@ macro_rules! extract_chain { ::ethjson::blockchain::Test::load(RAW_DATA).unwrap().into_iter() }}; - ($file:expr, $name:expr) => {{ - let mut chain = None; - for (name, c) in extract_chain!(iter $file) { - if name == $name { - chain = Some(c); - break; - } - } - chain.unwrap() - }}; - ($file:expr) => {{ - extract_chain!(iter $file).next().unwrap().1 + extract_chain!(iter $file).filter(|&(_, ref t)| t.network == ForkSpec::Frontier).next().unwrap().1 }}; } @@ -39,27 +28,7 @@ macro_rules! register_test { ($name:ident, $cb:expr, $file:expr) => { #[test] fn $name() { - for (name, chain) in extract_chain!(iter $file) { - $cb(name, chain); - } - } - }; - - (heavy $name:ident, $cb:expr, $file:expr) => { - #[test] - #[cfg(feature = "test-heavy")] - fn $name() { - for (name, chain) in extract_chain!(iter $file) { - $cb(name, chain); - } - } - }; - - (ignore $name:ident, $cb:expr, $file:expr) => { - #[test] - #[ignore] - fn $name() { - for (name, chain) in extract_chain!(iter $file) { + for (name, chain) in extract_chain!(iter $file).filter(|&(_, ref t)| t.network == ForkSpec::Frontier) { $cb(name, chain); } }