Merge pull request #103 from gavofyork/evm

EVM Interpreter
This commit is contained in:
Tomasz Drwięga 2016-01-17 11:54:04 +01:00
commit a350aae82b
19 changed files with 2162 additions and 128 deletions

View File

@ -20,5 +20,5 @@ time = "0.1"
evmjit = { path = "rust-evmjit", optional = true }
[features]
default = ["jit"]
jit = ["evmjit"]
evm_debug = []

View File

@ -0,0 +1,34 @@
{
"engineName": "Frontier (Test)",
"engineName": "Ethash",
"params": {
"accountStartNonce": "0x00",
"frontierCompatibilityModeLimit": "0x0dbba0",
"maximumExtraDataSize": "0x20",
"tieBreakingGas": false,
"minGasLimit": "0x1388",
"gasLimitBoundDivisor": "0x0400",
"minimumDifficulty": "0x020000",
"difficultyBoundDivisor": "0x0800",
"durationLimit": "0x0d",
"blockReward": "0x4563918244F40000",
"registrar" : "0xc6d9d2cd449a754c494264e1809c50e34d64562b",
"networkID" : "0x1"
},
"genesis": {
"nonce": "0x0000000000000042",
"difficulty": "0x400000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"author": "0x0000000000000000000000000000000000000000",
"timestamp": "0x00",
"parentHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
"gasLimit": "0x1388"
},
"accounts": {
"0000000000000000000000000000000000000001": { "builtin": { "name": "ecrecover", "linear": { "base": 3000, "word": 0 } } },
"0000000000000000000000000000000000000002": { "builtin": { "name": "sha256", "linear": { "base": 60, "word": 12 } } },
"0000000000000000000000000000000000000003": { "builtin": { "name": "ripemd160", "linear": { "base": 600, "word": 120 } } },
"0000000000000000000000000000000000000004": { "builtin": { "name": "identity", "linear": { "base": 15, "word": 3 } } }
}
}

View File

@ -2,6 +2,7 @@ use common::*;
use block::Block;
use spec::Spec;
use evm::Schedule;
use evm::Factory;
/// A consensus mechanism for the chain. Generally either proof-of-work or proof-of-stake-based.
/// Provides hooks into each of the major parts of block import.
@ -22,6 +23,9 @@ pub trait Engine : Sync + Send {
/// Get the general parameters of the chain.
fn spec(&self) -> &Spec;
/// Get current EVM factory
fn vm_factory(&self) -> &Factory;
/// Get the EVM schedule for the given `env_info`.
fn schedule(&self, env_info: &EnvInfo) -> Schedule;

View File

@ -3,11 +3,13 @@ use block::*;
use spec::*;
use engine::*;
use evm::Schedule;
use evm::Factory;
/// Engine using Ethash proof-of-work consensus algorithm, suitable for Ethereum
/// mainnet chains in the Olympic, Frontier and Homestead eras.
pub struct Ethash {
spec: Spec,
factory: Factory,
u64_params: RwLock<HashMap<String, u64>>,
u256_params: RwLock<HashMap<String, U256>>,
}
@ -16,8 +18,10 @@ impl Ethash {
pub fn new_boxed(spec: Spec) -> Box<Engine> {
Box::new(Ethash{
spec: spec,
// TODO [todr] should this return any specific factory?
factory: Factory::default(),
u64_params: RwLock::new(HashMap::new()),
u256_params: RwLock::new(HashMap::new()),
u256_params: RwLock::new(HashMap::new())
})
}
@ -43,6 +47,11 @@ impl Engine for Ethash {
/// Additional engine-specific information for the user/developer concerning `header`.
fn extra_info(&self, _header: &Header) -> HashMap<String, String> { HashMap::new() }
fn spec(&self) -> &Spec { &self.spec }
fn vm_factory(&self) -> &Factory {
&self.factory
}
fn schedule(&self, env_info: &EnvInfo) -> Schedule {
match env_info.number < self.u64_param("frontierCompatibilityModeLimit") {
true => Schedule::new_frontier(),

View File

@ -23,6 +23,9 @@ pub fn new_frontier_test() -> Spec { Spec::from_json_utf8(include_bytes!("../../
/// Create a new Homestead chain spec as though it never changed from Frontier.
pub fn new_homestead_test() -> Spec { Spec::from_json_utf8(include_bytes!("../../res/ethereum/homestead_test.json")) }
/// Create a new Frontier main net chain spec without genesis accounts.
pub fn new_frontier_like_test() -> Spec { Spec::from_json_utf8(include_bytes!("../../res/ethereum/frontier_like_test.json")) }
/// Create a new Morden chain spec.
pub fn new_morden() -> Spec { Spec::from_json_utf8(include_bytes!("../../res/ethereum/morden.json")) }

View File

@ -12,6 +12,28 @@ pub enum Error {
/// was invalid. Balance still should be transfered and nonce
/// should be increased.
OutOfGas,
/// `BadJumpDestination` is returned when execution tried to move
/// to position that wasn't marked with JUMPDEST instruction
BadJumpDestination {
destination: usize
},
/// `BadInstructions` is returned when given instruction is not supported
BadInstruction {
instruction: u8,
},
/// `StackUnderflow` when there is not enough stack elements to execute instruction
/// First parameter says how many elements were needed and the second how many were actually on Stack
StackUnderflow {
instruction: &'static str,
wanted: usize,
on_stack: usize
},
/// When execution would exceed defined Stack Limit
OutOfStack {
instruction: &'static str,
wanted: usize,
limit: usize
},
/// Returned on evm internal error. Should never be ignored during development.
/// Likely to cause consensus issues.
Internal,

View File

@ -1,8 +1,8 @@
//! Interface for Evm externalities.
use common::Bytes;
use util::hash::*;
use util::uint::*;
use util::bytes::*;
use evm::{Schedule, Error};
use env_info::*;
@ -61,10 +61,10 @@ pub trait Ext {
output: &mut [u8]) -> MessageCallResult;
/// Returns code at given address
fn extcode(&self, address: &Address) -> Vec<u8>;
fn extcode(&self, address: &Address) -> Bytes;
/// Creates log entry with given topics and data
fn log(&mut self, topics: Vec<H256>, data: Bytes);
fn log(&mut self, topics: Vec<H256>, data: &[u8]);
/// Should be called when transaction calls `RETURN` opcode.
/// Returns gas_left if cost of returning the data is not too high.

View File

@ -1,25 +1,123 @@
//! Evm factory.
use std::fmt;
use evm::Evm;
#[derive(Clone)]
pub enum VMType {
Jit,
Interpreter
}
impl fmt::Display for VMType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", match *self {
VMType::Jit => "JIT",
VMType::Interpreter => "INT"
})
}
}
impl VMType {
/// Return all possible VMs (JIT, Interpreter)
#[cfg(feature="jit")]
pub fn all() -> Vec<VMType> {
vec![VMType::Jit, VMType::Interpreter]
}
/// Return all possible VMs (Interpreter)
#[cfg(not(feature="jit"))]
pub fn all() -> Vec<VMType> {
vec![VMType::Interpreter]
}
}
/// Evm factory. Creates appropriate Evm.
pub struct Factory;
pub struct Factory {
evm : VMType
}
impl Factory {
/// Returns jit vm
/// Create fresh instance of VM
pub fn create(&self) -> Box<Evm> {
match self.evm {
VMType::Jit => {
Factory::jit()
},
VMType::Interpreter => {
Box::new(super::interpreter::Interpreter)
}
}
}
/// Create new instance of specific `VMType` factory
pub fn new(evm: VMType) -> Factory {
Factory {
evm: evm
}
}
#[cfg(feature = "jit")]
pub fn create() -> Box<Evm> {
fn jit() -> Box<Evm> {
Box::new(super::jit::JitEvm)
}
/// Returns native rust evm
#[cfg(not(feature = "jit"))]
pub fn create() -> Box<Evm> {
unimplemented!();
fn jit() -> Box<Evm> {
unimplemented!()
}
/// Returns jitvm factory
#[cfg(feature = "jit")]
pub fn default() -> Factory {
Factory {
evm: VMType::Jit
}
}
/// Returns native rust evm factory
#[cfg(not(feature = "jit"))]
pub fn default() -> Factory {
Factory {
evm: VMType::Interpreter
}
}
}
#[test]
fn test_create_vm() {
let _vm = Factory::create();
let _vm = Factory::default().create();
}
/// Create tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit));
}
#[test]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter));
}
}
);
/// Create ignored tests by injecting different VM factories
#[macro_export]
macro_rules! evm_test_ignore(
($name_test: ident: $name_jit: ident, $name_int: ident) => {
#[test]
#[ignore]
#[cfg(feature = "jit")]
fn $name_jit() {
$name_test(Factory::new(VMType::Jit));
}
#[test]
#[ignore]
fn $name_int() {
$name_test(Factory::new(VMType::Interpreter));
}
}
);

534
src/evm/instructions.rs Normal file
View File

@ -0,0 +1,534 @@
//! VM Instructions list and utility functions
pub type Instruction = u8;
/// Returns true if given instruction is `PUSHN` instruction.
pub fn is_push(i: Instruction) -> bool {
i >= PUSH1 && i <= PUSH32
}
/// Returns number of bytes to read for `PUSHN` instruction
/// PUSH1 -> 1
pub fn get_push_bytes(i: Instruction) -> usize {
assert!(is_push(i), "Only for PUSH instructions.");
(i - PUSH1 + 1) as usize
}
#[test]
fn test_get_push_bytes() {
assert_eq!(get_push_bytes(PUSH1), 1);
assert_eq!(get_push_bytes(PUSH3), 3);
assert_eq!(get_push_bytes(PUSH32), 32);
}
/// Returns stack position of item to duplicate
/// DUP1 -> 0
pub fn get_dup_position(i: Instruction) -> usize {
assert!(i >= DUP1 && i <= DUP16);
(i - DUP1) as usize
}
#[test]
fn test_get_dup_position() {
assert_eq!(get_dup_position(DUP1), 0);
assert_eq!(get_dup_position(DUP5), 4);
assert_eq!(get_dup_position(DUP10), 9);
}
/// Returns stack position of item to SWAP top with
/// SWAP1 -> 1
pub fn get_swap_position(i: Instruction) -> usize {
assert!(i >= SWAP1 && i <= SWAP16);
(i - SWAP1 + 1) as usize
}
#[test]
fn test_get_swap_position() {
assert_eq!(get_swap_position(SWAP1), 1);
assert_eq!(get_swap_position(SWAP5), 5);
assert_eq!(get_swap_position(SWAP10), 10);
}
/// Returns number of topcis to take from stack
/// LOG0 -> 0
pub fn get_log_topics (i: Instruction) -> usize {
assert!(i >= LOG0 && i <= LOG4);
(i - LOG0) as usize
}
#[test]
fn test_get_log_topics() {
assert_eq!(get_log_topics(LOG0), 0);
assert_eq!(get_log_topics(LOG2), 2);
assert_eq!(get_log_topics(LOG4), 4);
}
#[derive(PartialEq)]
pub enum GasPriceTier {
/// 0 Zero
Zero,
/// 2 Quick
Base,
/// 3 Fastest
VeryLow,
/// 5 Fast
Low,
/// 8 Mid
Mid,
/// 10 Slow
High,
/// 20 Ext
Ext,
/// Multiparam or otherwise special
Special,
/// Invalid
Invalid
}
/// Returns the index in schedule for specific `GasPriceTier`
pub fn get_tier_idx (tier: GasPriceTier) -> usize {
match tier {
GasPriceTier::Zero => 0,
GasPriceTier::Base => 1,
GasPriceTier::VeryLow => 2,
GasPriceTier::Low => 3,
GasPriceTier::Mid => 4,
GasPriceTier::High => 5,
GasPriceTier::Ext => 6,
GasPriceTier::Special => 7,
GasPriceTier::Invalid => 8
}
}
pub struct InstructionInfo {
pub name: &'static str,
pub additional: usize,
pub args: usize,
pub ret: usize,
pub side_effects: bool,
pub tier: GasPriceTier
}
impl InstructionInfo {
pub fn new(name: &'static str, additional: usize, args: usize, ret: usize, side_effects: bool, tier: GasPriceTier) -> InstructionInfo {
InstructionInfo {
name: name,
additional: additional,
args: args,
ret: ret,
side_effects: side_effects,
tier: tier
}
}
}
/// Return details about specific instruction
pub fn get_info (instruction: Instruction) -> InstructionInfo {
match instruction {
STOP => InstructionInfo::new("STOP", 0, 0, 0, true, GasPriceTier::Zero),
ADD => InstructionInfo::new("ADD", 0, 2, 1, false, GasPriceTier::VeryLow),
SUB => InstructionInfo::new("SUB", 0, 2, 1, false, GasPriceTier::VeryLow),
MUL => InstructionInfo::new("MUL", 0, 2, 1, false, GasPriceTier::Low),
DIV => InstructionInfo::new("DIV", 0, 2, 1, false, GasPriceTier::Low),
SDIV => InstructionInfo::new("SDIV", 0, 2, 1, false, GasPriceTier::Low),
MOD => InstructionInfo::new("MOD", 0, 2, 1, false, GasPriceTier::Low),
SMOD => InstructionInfo::new("SMOD", 0, 2, 1, false, GasPriceTier::Low),
EXP => InstructionInfo::new("EXP", 0, 2, 1, false, GasPriceTier::Special),
NOT => InstructionInfo::new("NOT", 0, 1, 1, false, GasPriceTier::VeryLow),
LT => InstructionInfo::new("LT", 0, 2, 1, false, GasPriceTier::VeryLow),
GT => InstructionInfo::new("GT", 0, 2, 1, false, GasPriceTier::VeryLow),
SLT => InstructionInfo::new("SLT", 0, 2, 1, false, GasPriceTier::VeryLow),
SGT => InstructionInfo::new("SGT", 0, 2, 1, false, GasPriceTier::VeryLow),
EQ => InstructionInfo::new("EQ", 0, 2, 1, false, GasPriceTier::VeryLow),
ISZERO => InstructionInfo::new("ISZERO", 0, 1, 1, false, GasPriceTier::VeryLow),
AND => InstructionInfo::new("AND", 0, 2, 1, false, GasPriceTier::VeryLow),
OR => InstructionInfo::new("OR", 0, 2, 1, false, GasPriceTier::VeryLow),
XOR => InstructionInfo::new("XOR", 0, 2, 1, false, GasPriceTier::VeryLow),
BYTE => InstructionInfo::new("BYTE", 0, 2, 1, false, GasPriceTier::VeryLow),
ADDMOD => InstructionInfo::new("ADDMOD", 0, 3, 1, false, GasPriceTier::Mid),
MULMOD => InstructionInfo::new("MULMOD", 0, 3, 1, false, GasPriceTier::Mid),
SIGNEXTEND => InstructionInfo::new("SIGNEXTEND", 0, 2, 1, false, GasPriceTier::Low),
SHA3 => InstructionInfo::new("SHA3", 0, 2, 1, false, GasPriceTier::Special),
ADDRESS => InstructionInfo::new("ADDRESS", 0, 0, 1, false, GasPriceTier::Base),
BALANCE => InstructionInfo::new("BALANCE", 0, 1, 1, false, GasPriceTier::Ext),
ORIGIN => InstructionInfo::new("ORIGIN", 0, 0, 1, false, GasPriceTier::Base),
CALLER => InstructionInfo::new("CALLER", 0, 0, 1, false, GasPriceTier::Base),
CALLVALUE => InstructionInfo::new("CALLVALUE", 0, 0, 1, false, GasPriceTier::Base),
CALLDATALOAD => InstructionInfo::new("CALLDATALOAD", 0, 1, 1, false, GasPriceTier::VeryLow),
CALLDATASIZE => InstructionInfo::new("CALLDATASIZE", 0, 0, 1, false, GasPriceTier::Base),
CALLDATACOPY => InstructionInfo::new("CALLDATACOPY", 0, 3, 0, true, GasPriceTier::VeryLow),
CODESIZE => InstructionInfo::new("CODESIZE", 0, 0, 1, false, GasPriceTier::Base),
CODECOPY => InstructionInfo::new("CODECOPY", 0, 3, 0, true, GasPriceTier::VeryLow),
GASPRICE => InstructionInfo::new("GASPRICE", 0, 0, 1, false, GasPriceTier::Base),
EXTCODESIZE => InstructionInfo::new("EXTCODESIZE", 0, 1, 1, false, GasPriceTier::Ext),
EXTCODECOPY => InstructionInfo::new("EXTCODECOPY", 0, 4, 0, true, GasPriceTier::Ext),
BLOCKHASH => InstructionInfo::new("BLOCKHASH", 0, 1, 1, false, GasPriceTier::Ext),
COINBASE => InstructionInfo::new("COINBASE", 0, 0, 1, false, GasPriceTier::Base),
TIMESTAMP => InstructionInfo::new("TIMESTAMP", 0, 0, 1, false, GasPriceTier::Base),
NUMBER => InstructionInfo::new("NUMBER", 0, 0, 1, false, GasPriceTier::Base),
DIFFICULTY => InstructionInfo::new("DIFFICULTY", 0, 0, 1, false, GasPriceTier::Base),
GASLIMIT => InstructionInfo::new("GASLIMIT", 0, 0, 1, false, GasPriceTier::Base),
POP => InstructionInfo::new("POP", 0, 1, 0, false, GasPriceTier::Base),
MLOAD => InstructionInfo::new("MLOAD", 0, 1, 1, false, GasPriceTier::VeryLow),
MSTORE => InstructionInfo::new("MSTORE", 0, 2, 0, true, GasPriceTier::VeryLow),
MSTORE8 => InstructionInfo::new("MSTORE8", 0, 2, 0, true, GasPriceTier::VeryLow),
SLOAD => InstructionInfo::new("SLOAD", 0, 1, 1, false, GasPriceTier::Special),
SSTORE => InstructionInfo::new("SSTORE", 0, 2, 0, true, GasPriceTier::Special),
JUMP => InstructionInfo::new("JUMP", 0, 1, 0, true, GasPriceTier::Mid),
JUMPI => InstructionInfo::new("JUMPI", 0, 2, 0, true, GasPriceTier::High),
PC => InstructionInfo::new("PC", 0, 0, 1, false, GasPriceTier::Base),
MSIZE => InstructionInfo::new("MSIZE", 0, 0, 1, false, GasPriceTier::Base),
GAS => InstructionInfo::new("GAS", 0, 0, 1, false, GasPriceTier::Base),
JUMPDEST => InstructionInfo::new("JUMPDEST", 0, 0, 0, true, GasPriceTier::Special),
PUSH1 => InstructionInfo::new("PUSH1", 1, 0, 1, false, GasPriceTier::VeryLow),
PUSH2 => InstructionInfo::new("PUSH2", 2, 0, 1, false, GasPriceTier::VeryLow),
PUSH3 => InstructionInfo::new("PUSH3", 3, 0, 1, false, GasPriceTier::VeryLow),
PUSH4 => InstructionInfo::new("PUSH4", 4, 0, 1, false, GasPriceTier::VeryLow),
PUSH5 => InstructionInfo::new("PUSH5", 5, 0, 1, false, GasPriceTier::VeryLow),
PUSH6 => InstructionInfo::new("PUSH6", 6, 0, 1, false, GasPriceTier::VeryLow),
PUSH7 => InstructionInfo::new("PUSH7", 7, 0, 1, false, GasPriceTier::VeryLow),
PUSH8 => InstructionInfo::new("PUSH8", 8, 0, 1, false, GasPriceTier::VeryLow),
PUSH9 => InstructionInfo::new("PUSH9", 9, 0, 1, false, GasPriceTier::VeryLow),
PUSH10 => InstructionInfo::new("PUSH10", 10, 0, 1, false, GasPriceTier::VeryLow),
PUSH11 => InstructionInfo::new("PUSH11", 11, 0, 1, false, GasPriceTier::VeryLow),
PUSH12 => InstructionInfo::new("PUSH12", 12, 0, 1, false, GasPriceTier::VeryLow),
PUSH13 => InstructionInfo::new("PUSH13", 13, 0, 1, false, GasPriceTier::VeryLow),
PUSH14 => InstructionInfo::new("PUSH14", 14, 0, 1, false, GasPriceTier::VeryLow),
PUSH15 => InstructionInfo::new("PUSH15", 15, 0, 1, false, GasPriceTier::VeryLow),
PUSH16 => InstructionInfo::new("PUSH16", 16, 0, 1, false, GasPriceTier::VeryLow),
PUSH17 => InstructionInfo::new("PUSH17", 17, 0, 1, false, GasPriceTier::VeryLow),
PUSH18 => InstructionInfo::new("PUSH18", 18, 0, 1, false, GasPriceTier::VeryLow),
PUSH19 => InstructionInfo::new("PUSH19", 19, 0, 1, false, GasPriceTier::VeryLow),
PUSH20 => InstructionInfo::new("PUSH20", 20, 0, 1, false, GasPriceTier::VeryLow),
PUSH21 => InstructionInfo::new("PUSH21", 21, 0, 1, false, GasPriceTier::VeryLow),
PUSH22 => InstructionInfo::new("PUSH22", 22, 0, 1, false, GasPriceTier::VeryLow),
PUSH23 => InstructionInfo::new("PUSH23", 23, 0, 1, false, GasPriceTier::VeryLow),
PUSH24 => InstructionInfo::new("PUSH24", 24, 0, 1, false, GasPriceTier::VeryLow),
PUSH25 => InstructionInfo::new("PUSH25", 25, 0, 1, false, GasPriceTier::VeryLow),
PUSH26 => InstructionInfo::new("PUSH26", 26, 0, 1, false, GasPriceTier::VeryLow),
PUSH27 => InstructionInfo::new("PUSH27", 27, 0, 1, false, GasPriceTier::VeryLow),
PUSH28 => InstructionInfo::new("PUSH28", 28, 0, 1, false, GasPriceTier::VeryLow),
PUSH29 => InstructionInfo::new("PUSH29", 29, 0, 1, false, GasPriceTier::VeryLow),
PUSH30 => InstructionInfo::new("PUSH30", 30, 0, 1, false, GasPriceTier::VeryLow),
PUSH31 => InstructionInfo::new("PUSH31", 31, 0, 1, false, GasPriceTier::VeryLow),
PUSH32 => InstructionInfo::new("PUSH32", 32, 0, 1, false, GasPriceTier::VeryLow),
DUP1 => InstructionInfo::new("DUP1", 0, 1, 2, false, GasPriceTier::VeryLow),
DUP2 => InstructionInfo::new("DUP2", 0, 2, 3, false, GasPriceTier::VeryLow),
DUP3 => InstructionInfo::new("DUP3", 0, 3, 4, false, GasPriceTier::VeryLow),
DUP4 => InstructionInfo::new("DUP4", 0, 4, 5, false, GasPriceTier::VeryLow),
DUP5 => InstructionInfo::new("DUP5", 0, 5, 6, false, GasPriceTier::VeryLow),
DUP6 => InstructionInfo::new("DUP6", 0, 6, 7, false, GasPriceTier::VeryLow),
DUP7 => InstructionInfo::new("DUP7", 0, 7, 8, false, GasPriceTier::VeryLow),
DUP8 => InstructionInfo::new("DUP8", 0, 8, 9, false, GasPriceTier::VeryLow),
DUP9 => InstructionInfo::new("DUP9", 0, 9, 10, false, GasPriceTier::VeryLow),
DUP10 => InstructionInfo::new("DUP10", 0, 10, 11, false, GasPriceTier::VeryLow),
DUP11 => InstructionInfo::new("DUP11", 0, 11, 12, false, GasPriceTier::VeryLow),
DUP12 => InstructionInfo::new("DUP12", 0, 12, 13, false, GasPriceTier::VeryLow),
DUP13 => InstructionInfo::new("DUP13", 0, 13, 14, false, GasPriceTier::VeryLow),
DUP14 => InstructionInfo::new("DUP14", 0, 14, 15, false, GasPriceTier::VeryLow),
DUP15 => InstructionInfo::new("DUP15", 0, 15, 16, false, GasPriceTier::VeryLow),
DUP16 => InstructionInfo::new("DUP16", 0, 16, 17, false, GasPriceTier::VeryLow),
SWAP1 => InstructionInfo::new("SWAP1", 0, 2, 2, false, GasPriceTier::VeryLow),
SWAP2 => InstructionInfo::new("SWAP2", 0, 3, 3, false, GasPriceTier::VeryLow),
SWAP3 => InstructionInfo::new("SWAP3", 0, 4, 4, false, GasPriceTier::VeryLow),
SWAP4 => InstructionInfo::new("SWAP4", 0, 5, 5, false, GasPriceTier::VeryLow),
SWAP5 => InstructionInfo::new("SWAP5", 0, 6, 6, false, GasPriceTier::VeryLow),
SWAP6 => InstructionInfo::new("SWAP6", 0, 7, 7, false, GasPriceTier::VeryLow),
SWAP7 => InstructionInfo::new("SWAP7", 0, 8, 8, false, GasPriceTier::VeryLow),
SWAP8 => InstructionInfo::new("SWAP8", 0, 9, 9, false, GasPriceTier::VeryLow),
SWAP9 => InstructionInfo::new("SWAP9", 0, 10, 10, false, GasPriceTier::VeryLow),
SWAP10 => InstructionInfo::new("SWAP10", 0, 11, 11, false, GasPriceTier::VeryLow),
SWAP11 => InstructionInfo::new("SWAP11", 0, 12, 12, false, GasPriceTier::VeryLow),
SWAP12 => InstructionInfo::new("SWAP12", 0, 13, 13, false, GasPriceTier::VeryLow),
SWAP13 => InstructionInfo::new("SWAP13", 0, 14, 14, false, GasPriceTier::VeryLow),
SWAP14 => InstructionInfo::new("SWAP14", 0, 15, 15, false, GasPriceTier::VeryLow),
SWAP15 => InstructionInfo::new("SWAP15", 0, 16, 16, false, GasPriceTier::VeryLow),
SWAP16 => InstructionInfo::new("SWAP16", 0, 17, 17, false, GasPriceTier::VeryLow),
LOG0 => InstructionInfo::new("LOG0", 0, 2, 0, true, GasPriceTier::Special),
LOG1 => InstructionInfo::new("LOG1", 0, 3, 0, true, GasPriceTier::Special),
LOG2 => InstructionInfo::new("LOG2", 0, 4, 0, true, GasPriceTier::Special),
LOG3 => InstructionInfo::new("LOG3", 0, 5, 0, true, GasPriceTier::Special),
LOG4 => InstructionInfo::new("LOG4", 0, 6, 0, true, GasPriceTier::Special),
CREATE => InstructionInfo::new("CREATE", 0, 3, 1, true, GasPriceTier::Special),
CALL => InstructionInfo::new("CALL", 0, 7, 1, true, GasPriceTier::Special),
CALLCODE => InstructionInfo::new("CALLCODE", 0, 7, 1, true, GasPriceTier::Special),
RETURN => InstructionInfo::new("RETURN", 0, 2, 0, true, GasPriceTier::Zero),
DELEGATECALL => InstructionInfo::new("DELEGATECALL", 0, 6, 1, true, GasPriceTier::Special),
SUICIDE => InstructionInfo::new("SUICIDE", 0, 1, 0, true, GasPriceTier::Zero),
_ => InstructionInfo::new("INVALID_INSTRUCTION", 0, 0, 0, false, GasPriceTier::Invalid)
}
}
/// Virtual machine bytecode instruction.
/// halts execution
pub const STOP: Instruction = 0x00;
/// addition operation
pub const ADD: Instruction = 0x01;
/// mulitplication operation
pub const MUL: Instruction = 0x02;
/// subtraction operation
pub const SUB: Instruction = 0x03;
/// integer division operation
pub const DIV: Instruction = 0x04;
/// signed integer division operation
pub const SDIV: Instruction = 0x05;
/// modulo remainder operation
pub const MOD: Instruction = 0x06;
/// signed modulo remainder operation
pub const SMOD: Instruction = 0x07;
/// unsigned modular addition
pub const ADDMOD: Instruction = 0x08;
/// unsigned modular multiplication
pub const MULMOD: Instruction = 0x09;
/// exponential operation
pub const EXP: Instruction = 0x0a;
/// extend length of signed integer
pub const SIGNEXTEND: Instruction = 0x0b;
/// less-than comparision
pub const LT: Instruction = 0x10;
/// greater-than comparision
pub const GT: Instruction = 0x11;
/// signed less-than comparision
pub const SLT: Instruction = 0x12;
/// signed greater-than comparision
pub const SGT: Instruction = 0x13;
/// equality comparision
pub const EQ: Instruction = 0x14;
/// simple not operator
pub const ISZERO: Instruction = 0x15;
/// bitwise AND operation
pub const AND: Instruction = 0x16;
/// bitwise OR operation
pub const OR: Instruction = 0x17;
/// bitwise XOR operation
pub const XOR: Instruction = 0x18;
/// bitwise NOT opertation
pub const NOT: Instruction = 0x19;
/// retrieve single byte from word
pub const BYTE: Instruction = 0x1a;
/// compute SHA3-256 hash
pub const SHA3: Instruction = 0x20;
/// get address of currently executing account
pub const ADDRESS: Instruction = 0x30;
/// get balance of the given account
pub const BALANCE: Instruction = 0x31;
/// get execution origination address
pub const ORIGIN: Instruction = 0x32;
/// get caller address
pub const CALLER: Instruction = 0x33;
/// get deposited value by the instruction/transaction responsible for this execution
pub const CALLVALUE: Instruction = 0x34;
/// get input data of current environment
pub const CALLDATALOAD: Instruction = 0x35;
/// get size of input data in current environment
pub const CALLDATASIZE: Instruction = 0x36;
/// copy input data in current environment to memory
pub const CALLDATACOPY: Instruction = 0x37;
/// get size of code running in current environment
pub const CODESIZE: Instruction = 0x38;
/// copy code running in current environment to memory
pub const CODECOPY: Instruction = 0x39;
/// get price of gas in current environment
pub const GASPRICE: Instruction = 0x3a;
/// get external code size (from another contract)
pub const EXTCODESIZE: Instruction = 0x3b;
/// copy external code (from another contract)
pub const EXTCODECOPY: Instruction = 0x3c;
/// get hash of most recent complete block
pub const BLOCKHASH: Instruction = 0x40;
/// get the block's coinbase address
pub const COINBASE: Instruction = 0x41;
/// get the block's timestamp
pub const TIMESTAMP: Instruction = 0x42;
/// get the block's number
pub const NUMBER: Instruction = 0x43;
/// get the block's difficulty
pub const DIFFICULTY: Instruction = 0x44;
/// get the block's gas limit
pub const GASLIMIT: Instruction = 0x45;
/// remove item from stack
pub const POP: Instruction = 0x50;
/// load word from memory
pub const MLOAD: Instruction = 0x51;
/// save word to memory
pub const MSTORE: Instruction = 0x52;
/// save byte to memory
pub const MSTORE8: Instruction = 0x53;
/// load word from storage
pub const SLOAD: Instruction = 0x54;
/// save word to storage
pub const SSTORE: Instruction = 0x55;
/// alter the program counter
pub const JUMP: Instruction = 0x56;
/// conditionally alter the program counter
pub const JUMPI: Instruction = 0x57;
/// get the program counter
pub const PC: Instruction = 0x58;
/// get the size of active memory
pub const MSIZE: Instruction = 0x59;
/// get the amount of available gas
pub const GAS: Instruction = 0x5a;
/// set a potential jump destination
pub const JUMPDEST: Instruction = 0x5b;
/// place 1 byte item on stack
pub const PUSH1: Instruction = 0x60;
/// place 2 byte item on stack
pub const PUSH2: Instruction = 0x61;
/// place 3 byte item on stack
pub const PUSH3: Instruction = 0x62;
/// place 4 byte item on stack
pub const PUSH4: Instruction = 0x63;
/// place 5 byte item on stack
pub const PUSH5: Instruction = 0x64;
/// place 6 byte item on stack
pub const PUSH6: Instruction = 0x65;
/// place 7 byte item on stack
pub const PUSH7: Instruction = 0x66;
/// place 8 byte item on stack
pub const PUSH8: Instruction = 0x67;
/// place 9 byte item on stack
pub const PUSH9: Instruction = 0x68;
/// place 10 byte item on stack
pub const PUSH10: Instruction = 0x69;
/// place 11 byte item on stack
pub const PUSH11: Instruction = 0x6a;
/// place 12 byte item on stack
pub const PUSH12: Instruction = 0x6b;
/// place 13 byte item on stack
pub const PUSH13: Instruction = 0x6c;
/// place 14 byte item on stack
pub const PUSH14: Instruction = 0x6d;
/// place 15 byte item on stack
pub const PUSH15: Instruction = 0x6e;
/// place 16 byte item on stack
pub const PUSH16: Instruction = 0x6f;
/// place 17 byte item on stack
pub const PUSH17: Instruction = 0x70;
/// place 18 byte item on stack
pub const PUSH18: Instruction = 0x71;
/// place 19 byte item on stack
pub const PUSH19: Instruction = 0x72;
/// place 20 byte item on stack
pub const PUSH20: Instruction = 0x73;
/// place 21 byte item on stack
pub const PUSH21: Instruction = 0x74;
/// place 22 byte item on stack
pub const PUSH22: Instruction = 0x75;
/// place 23 byte item on stack
pub const PUSH23: Instruction = 0x76;
/// place 24 byte item on stack
pub const PUSH24: Instruction = 0x77;
/// place 25 byte item on stack
pub const PUSH25: Instruction = 0x78;
/// place 26 byte item on stack
pub const PUSH26: Instruction = 0x79;
/// place 27 byte item on stack
pub const PUSH27: Instruction = 0x7a;
/// place 28 byte item on stack
pub const PUSH28: Instruction = 0x7b;
/// place 29 byte item on stack
pub const PUSH29: Instruction = 0x7c;
/// place 30 byte item on stack
pub const PUSH30: Instruction = 0x7d;
/// place 31 byte item on stack
pub const PUSH31: Instruction = 0x7e;
/// place 32 byte item on stack
pub const PUSH32: Instruction = 0x7f;
/// copies the highest item in the stack to the top of the stack
pub const DUP1: Instruction = 0x80;
/// copies the second highest item in the stack to the top of the stack
pub const DUP2: Instruction = 0x81;
/// copies the third highest item in the stack to the top of the stack
pub const DUP3: Instruction = 0x82;
/// copies the 4th highest item in the stack to the top of the stack
pub const DUP4: Instruction = 0x83;
/// copies the 5th highest item in the stack to the top of the stack
pub const DUP5: Instruction = 0x84;
/// copies the 6th highest item in the stack to the top of the stack
pub const DUP6: Instruction = 0x85;
/// copies the 7th highest item in the stack to the top of the stack
pub const DUP7: Instruction = 0x86;
/// copies the 8th highest item in the stack to the top of the stack
pub const DUP8: Instruction = 0x87;
/// copies the 9th highest item in the stack to the top of the stack
pub const DUP9: Instruction = 0x88;
/// copies the 10th highest item in the stack to the top of the stack
pub const DUP10: Instruction = 0x89;
/// copies the 11th highest item in the stack to the top of the stack
pub const DUP11: Instruction = 0x8a;
/// copies the 12th highest item in the stack to the top of the stack
pub const DUP12: Instruction = 0x8b;
/// copies the 13th highest item in the stack to the top of the stack
pub const DUP13: Instruction = 0x8c;
/// copies the 14th highest item in the stack to the top of the stack
pub const DUP14: Instruction = 0x8d;
/// copies the 15th highest item in the stack to the top of the stack
pub const DUP15: Instruction = 0x8e;
/// copies the 16th highest item in the stack to the top of the stack
pub const DUP16: Instruction = 0x8f;
/// swaps the highest and second highest value on the stack
pub const SWAP1: Instruction = 0x90;
/// swaps the highest and third highest value on the stack
pub const SWAP2: Instruction = 0x91;
/// swaps the highest and 4th highest value on the stack
pub const SWAP3: Instruction = 0x92;
/// swaps the highest and 5th highest value on the stack
pub const SWAP4: Instruction = 0x93;
/// swaps the highest and 6th highest value on the stack
pub const SWAP5: Instruction = 0x94;
/// swaps the highest and 7th highest value on the stack
pub const SWAP6: Instruction = 0x95;
/// swaps the highest and 8th highest value on the stack
pub const SWAP7: Instruction = 0x96;
/// swaps the highest and 9th highest value on the stack
pub const SWAP8: Instruction = 0x97;
/// swaps the highest and 10th highest value on the stack
pub const SWAP9: Instruction = 0x98;
/// swaps the highest and 11th highest value on the stack
pub const SWAP10: Instruction = 0x99;
/// swaps the highest and 12th highest value on the stack
pub const SWAP11: Instruction = 0x9a;
/// swaps the highest and 13th highest value on the stack
pub const SWAP12: Instruction = 0x9b;
/// swaps the highest and 14th highest value on the stack
pub const SWAP13: Instruction = 0x9c;
/// swaps the highest and 15th highest value on the stack
pub const SWAP14: Instruction = 0x9d;
/// swaps the highest and 16th highest value on the stack
pub const SWAP15: Instruction = 0x9e;
/// swaps the highest and 17th highest value on the stack
pub const SWAP16: Instruction = 0x9f;
/// Makes a log entry; no topics.
pub const LOG0: Instruction = 0xa0;
/// Makes a log entry; 1 topic.
pub const LOG1: Instruction = 0xa1;
/// Makes a log entry; 2 topics.
pub const LOG2: Instruction = 0xa2;
/// Makes a log entry; 3 topics.
pub const LOG3: Instruction = 0xa3;
/// Makes a log entry; 4 topics.
pub const LOG4: Instruction = 0xa4;
/// Maximal number of topics for log instructions
pub const MAX_NO_OF_TOPICS : usize = 4;
/// create a new account with associated code
pub const CREATE: Instruction = 0xf0;
/// message-call into an account
pub const CALL: Instruction = 0xf1;
/// message-call with another account's code only
pub const CALLCODE: Instruction = 0xf2;
/// halt execution returning output data
pub const RETURN: Instruction = 0xf3;
/// like CALLCODE but keeps caller's value and sender
pub const DELEGATECALL: Instruction = 0xf4;
/// halt execution and register account for later deletion
pub const SUICIDE: Instruction = 0xff;

1210
src/evm/interpreter.rs Normal file

File diff suppressed because it is too large Load Diff

View File

@ -2,8 +2,11 @@
pub mod ext;
pub mod evm;
pub mod interpreter;
#[macro_use]
pub mod factory;
pub mod schedule;
mod instructions;
#[cfg(feature = "jit" )]
mod jit;
@ -14,3 +17,4 @@ pub use self::evm::{Evm, Error, Result};
pub use self::ext::{Ext, ContractCreateResult, MessageCallResult};
pub use self::factory::Factory;
pub use self::schedule::Schedule;
pub use self::factory::VMType;

View File

@ -1,6 +1,6 @@
use common::*;
use evm;
use evm::{Ext, Schedule, Factory, ContractCreateResult, MessageCallResult};
use evm::{Ext, Schedule, Factory, VMType, ContractCreateResult, MessageCallResult};
struct FakeLogEntry {
topics: Vec<H256>,
@ -18,11 +18,20 @@ struct FakeExt {
codes: HashMap<Address, Bytes>,
logs: Vec<FakeLogEntry>,
_suicides: HashSet<Address>,
info: EnvInfo
info: EnvInfo,
_schedule: Schedule
}
impl FakeExt {
fn new() -> Self { FakeExt::default() }
fn new() -> Self {
FakeExt::default()
}
}
impl Default for Schedule {
fn default() -> Self {
Schedule::new_frontier()
}
}
impl Ext for FakeExt {
@ -60,14 +69,14 @@ impl Ext for FakeExt {
unimplemented!();
}
fn extcode(&self, address: &Address) -> Vec<u8> {
fn extcode(&self, address: &Address) -> Bytes {
self.codes.get(address).unwrap_or(&Bytes::new()).clone()
}
fn log(&mut self, topics: Vec<H256>, data: Bytes) {
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
self.logs.push(FakeLogEntry {
topics: topics,
data: data
data: data.to_vec()
});
}
@ -80,7 +89,7 @@ impl Ext for FakeExt {
}
fn schedule(&self) -> &Schedule {
unimplemented!();
&self._schedule
}
fn env_info(&self) -> &EnvInfo {
@ -97,8 +106,35 @@ impl Ext for FakeExt {
}
#[test]
fn test_add() {
fn test_stack_underflow() {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "01600055".from_hex().unwrap();
let mut params = ActionParams::new();
params.address = address.clone();
params.gas = U256::from(100_000);
params.code = Some(code);
let mut ext = FakeExt::new();
let err = {
let vm : Box<evm::Evm> = Box::new(super::interpreter::Interpreter);
vm.exec(params, &mut ext).unwrap_err()
};
match err {
evm::Error::StackUnderflow {instruction: _, wanted, on_stack} => {
assert_eq!(wanted, 2);
assert_eq!(on_stack, 0);
}
_ => {
assert!(false, "Expected StackUndeflow")
}
};
}
evm_test!{test_add: test_add_jit, test_add_int}
fn test_add(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff01600055".from_hex().unwrap();
let mut params = ActionParams::new();
@ -108,7 +144,7 @@ fn test_add() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -116,8 +152,8 @@ fn test_add() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe").unwrap());
}
#[test]
fn test_sha3() {
evm_test!{test_sha3: test_sha3_jit, test_sha3_int}
fn test_sha3(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "6000600020600055".from_hex().unwrap();
@ -128,7 +164,7 @@ fn test_sha3() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -136,8 +172,8 @@ fn test_sha3() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470").unwrap());
}
#[test]
fn test_address() {
evm_test!{test_address: test_address_jit, test_address_int}
fn test_address(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "30600055".from_hex().unwrap();
@ -148,7 +184,7 @@ fn test_address() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -156,8 +192,8 @@ fn test_address() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap());
}
#[test]
fn test_origin() {
evm_test!{test_origin: test_origin_jit, test_origin_int}
fn test_origin(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let origin = Address::from_str("cd1722f2947def4cf144679da39c4c32bdc35681").unwrap();
let code = "32600055".from_hex().unwrap();
@ -170,7 +206,7 @@ fn test_origin() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -178,8 +214,8 @@ fn test_origin() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("000000000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681").unwrap());
}
#[test]
fn test_sender() {
evm_test!{test_sender: test_sender_jit, test_sender_int}
fn test_sender(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let sender = Address::from_str("cd1722f2947def4cf144679da39c4c32bdc35681").unwrap();
let code = "33600055".from_hex().unwrap();
@ -192,7 +228,7 @@ fn test_sender() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -200,8 +236,8 @@ fn test_sender() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("000000000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681").unwrap());
}
#[test]
fn test_extcodecopy() {
evm_test!{test_extcodecopy: test_extcodecopy_jit, test_extcodecopy_int}
fn test_extcodecopy(factory: super::Factory) {
// 33 - sender
// 3b - extcodesize
// 60 00 - push 0
@ -227,7 +263,7 @@ fn test_extcodecopy() {
ext.codes.insert(sender, sender_code);
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -235,8 +271,8 @@ fn test_extcodecopy() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("6005600055000000000000000000000000000000000000000000000000000000").unwrap());
}
#[test]
fn test_log_empty() {
evm_test!{test_log_empty: test_log_empty_jit, test_log_empty_int}
fn test_log_empty(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "60006000a0".from_hex().unwrap();
@ -247,7 +283,7 @@ fn test_log_empty() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -257,8 +293,8 @@ fn test_log_empty() {
assert_eq!(ext.logs[0].data, vec![]);
}
#[test]
fn test_log_sender() {
evm_test!{test_log_sender: test_log_sender_jit, test_log_sender_int}
fn test_log_sender(factory: super::Factory) {
// 60 ff - push ff
// 60 00 - push 00
// 53 - mstore
@ -279,7 +315,7 @@ fn test_log_sender() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -290,8 +326,8 @@ fn test_log_sender() {
assert_eq!(ext.logs[0].data, "ff00000000000000000000000000000000000000000000000000000000000000".from_hex().unwrap());
}
#[test]
fn test_blockhash() {
evm_test!{test_blockhash: test_blockhash_jit, test_blockhash_int}
fn test_blockhash(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "600040600055".from_hex().unwrap();
let blockhash = H256::from_str("123400000000000000000000cd1722f2947def4cf144679da39c4c32bdc35681").unwrap();
@ -304,7 +340,7 @@ fn test_blockhash() {
ext.blockhashes.insert(U256::zero(), blockhash.clone());
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -312,8 +348,8 @@ fn test_blockhash() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &blockhash);
}
#[test]
fn test_calldataload() {
evm_test!{test_calldataload: test_calldataload_jit, test_calldataload_int}
fn test_calldataload(factory: super::Factory) {
let address = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "600135600055".from_hex().unwrap();
let data = "0123ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff23".from_hex().unwrap();
@ -326,7 +362,7 @@ fn test_calldataload() {
let mut ext = FakeExt::new();
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -335,8 +371,8 @@ fn test_calldataload() {
}
#[test]
fn test_author() {
evm_test!{test_author: test_author_jit, test_author_int}
fn test_author(factory: super::Factory) {
let author = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let code = "41600055".from_hex().unwrap();
@ -347,7 +383,7 @@ fn test_author() {
ext.info.author = author;
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -355,8 +391,8 @@ fn test_author() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap());
}
#[test]
fn test_timestamp() {
evm_test!{test_timestamp: test_timestamp_jit, test_timestamp_int}
fn test_timestamp(factory: super::Factory) {
let timestamp = 0x1234;
let code = "42600055".from_hex().unwrap();
@ -367,7 +403,7 @@ fn test_timestamp() {
ext.info.timestamp = timestamp;
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -375,8 +411,8 @@ fn test_timestamp() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000000000000000000000000000000000000001234").unwrap());
}
#[test]
fn test_number() {
evm_test!{test_number: test_number_jit, test_number_int}
fn test_number(factory: super::Factory) {
let number = 0x1234;
let code = "43600055".from_hex().unwrap();
@ -387,7 +423,7 @@ fn test_number() {
ext.info.number = number;
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -395,8 +431,8 @@ fn test_number() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000000000000000000000000000000000000001234").unwrap());
}
#[test]
fn test_difficulty() {
evm_test!{test_difficulty: test_difficulty_jit, test_difficulty_int}
fn test_difficulty(factory: super::Factory) {
let difficulty = U256::from(0x1234);
let code = "44600055".from_hex().unwrap();
@ -407,7 +443,7 @@ fn test_difficulty() {
ext.info.difficulty = difficulty;
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
@ -415,8 +451,8 @@ fn test_difficulty() {
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000000000000000000000000000000000000001234").unwrap());
}
#[test]
fn test_gas_limit() {
evm_test!{test_gas_limit: test_gas_limit_jit, test_gas_limit_int}
fn test_gas_limit(factory: super::Factory) {
let gas_limit = U256::from(0x1234);
let code = "45600055".from_hex().unwrap();
@ -427,10 +463,11 @@ fn test_gas_limit() {
ext.info.gas_limit = gas_limit;
let gas_left = {
let vm = Factory::create();
let vm = factory.create();
vm.exec(params, &mut ext).unwrap()
};
assert_eq!(gas_left, U256::from(79_995));
assert_eq!(ext.store.get(&H256::new()).unwrap(), &H256::from_str("0000000000000000000000000000000000000000000000000000000000001234").unwrap());
}

View File

@ -2,7 +2,7 @@
use common::*;
use state::*;
use engine::*;
use evm::{self, Factory, Ext};
use evm::{self, Ext};
use externalities::*;
use substate::*;
@ -199,8 +199,7 @@ impl<'a> Executive<'a> {
let res = {
let mut ext = self.to_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::Return(output));
let evm = Factory::create();
evm.exec(params, &mut ext)
self.engine.vm_factory().create().exec(params, &mut ext)
};
trace!("exec: sstore-clears={}\n", unconfirmed_substate.sstore_clears_count);
@ -232,8 +231,7 @@ impl<'a> Executive<'a> {
let res = {
let mut ext = self.to_externalities(OriginInfo::from(&params), &mut unconfirmed_substate, OutputPolicy::InitContract);
let evm = Factory::create();
evm.exec(params, &mut ext)
self.engine.vm_factory().create().exec(params, &mut ext)
};
self.enact_result(&res, substate, unconfirmed_substate, backup);
res
@ -274,6 +272,21 @@ impl<'a> Executive<'a> {
match result {
Err(evm::Error::Internal) => Err(ExecutionError::Internal),
// TODO [ToDr] BadJumpDestination @debris - how to handle that?
Err(evm::Error::OutOfGas)
| Err(evm::Error::BadJumpDestination { destination: _ })
| Err(evm::Error::BadInstruction { instruction: _ })
| Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
| Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
Ok(Executed {
gas: t.gas,
gas_used: t.gas,
refunded: U256::zero(),
cumulative_gas_used: self.info.gas_used + t.gas,
logs: vec![],
contracts_created: vec![]
})
},
_ => {
Ok(Executed {
gas: t.gas,
@ -290,7 +303,11 @@ impl<'a> Executive<'a> {
fn enact_result(&mut self, result: &evm::Result, substate: &mut Substate, un_substate: Substate, backup: State) {
// TODO: handle other evm::Errors same as OutOfGas once they are implemented
match result {
&Err(evm::Error::OutOfGas) => {
&Err(evm::Error::OutOfGas)
| &Err(evm::Error::BadJumpDestination { destination: _ })
| &Err(evm::Error::BadInstruction { instruction: _ })
| &Err(evm::Error::StackUnderflow {instruction: _, wanted: _, on_stack: _})
| &Err(evm::Error::OutOfStack {instruction: _, wanted: _, limit: _}) => {
self.state.revert(backup);
},
&Ok(_) | &Err(evm::Error::Internal) => substate.accrue(un_substate)
@ -306,17 +323,19 @@ mod tests {
use ethereum;
use engine::*;
use spec::*;
use evm::Schedule;
use evm::{Schedule, Factory, VMType};
use substate::*;
struct TestEngine {
factory: Factory,
spec: Spec,
max_depth: usize
}
impl TestEngine {
fn new(max_depth: usize) -> TestEngine {
fn new(max_depth: usize, factory: Factory) -> TestEngine {
TestEngine {
factory: factory,
spec: ethereum::new_frontier_test(),
max_depth: max_depth
}
@ -326,6 +345,9 @@ mod tests {
impl Engine for TestEngine {
fn name(&self) -> &str { "TestEngine" }
fn spec(&self) -> &Spec { &self.spec }
fn vm_factory(&self) -> &Factory {
&self.factory
}
fn schedule(&self, _env_info: &EnvInfo) -> Schedule {
let mut schedule = Schedule::new_frontier();
schedule.max_depth = self.max_depth;
@ -340,9 +362,9 @@ mod tests {
assert_eq!(expected_address, contract_address(&address, &U256::from(88)));
}
#[test]
// TODO: replace params with transactions!
fn test_sender_balance() {
evm_test!{test_sender_balance: test_sender_balance_jit, test_sender_balance_int}
fn test_sender_balance(factory: Factory) {
let sender = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let address = contract_address(&sender, &U256::zero());
let mut params = ActionParams::new();
@ -354,7 +376,7 @@ mod tests {
let mut state = State::new_temp();
state.add_balance(&sender, &U256::from(0x100u64));
let info = EnvInfo::new();
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let gas_left = {
@ -372,8 +394,8 @@ mod tests {
// TODO: just test state root.
}
#[test]
fn test_create_contract() {
evm_test!{test_create_contract: test_create_contract_jit, test_create_contract_int}
fn test_create_contract(factory: Factory) {
// code:
//
// 7c 601080600c6000396000f3006000355415600957005b60203560003555 - push 29 bytes?
@ -412,7 +434,7 @@ mod tests {
let mut state = State::new_temp();
state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::new();
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let gas_left = {
@ -425,8 +447,8 @@ mod tests {
assert_eq!(substate.contracts_created.len(), 0);
}
#[test]
fn test_create_contract_value_too_high() {
evm_test!{test_create_contract_value_too_high: test_create_contract_value_too_high_jit, test_create_contract_value_too_high_int}
fn test_create_contract_value_too_high(factory: Factory) {
// code:
//
// 7c 601080600c6000396000f3006000355415600957005b60203560003555 - push 29 bytes?
@ -465,7 +487,7 @@ mod tests {
let mut state = State::new_temp();
state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::new();
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let gas_left = {
@ -477,8 +499,8 @@ mod tests {
assert_eq!(substate.contracts_created.len(), 0);
}
#[test]
fn test_create_contract_without_max_depth() {
evm_test!{test_create_contract_without_max_depth: test_create_contract_without_max_depth_jit, test_create_contract_without_max_depth_int}
fn test_create_contract_without_max_depth(factory: Factory) {
// code:
//
// 7c 601080600c6000396000f3006000355415600957005b60203560003555 - push 29 bytes?
@ -501,7 +523,7 @@ mod tests {
// 60 00 - push 0
// f3 - return
let code = "7c601080600c6000396000f3006000355415600957005b60203560003555600052601d60036017f0600055".from_hex().unwrap();
let code = "7c601080600c6000396000f3006000355415600957005b60203560003555600052601d60036017f0".from_hex().unwrap();
let sender = Address::from_str("cd1722f3947def4cf144679da39c4c32bdc35681").unwrap();
let address = contract_address(&sender, &U256::zero());
@ -516,7 +538,7 @@ mod tests {
let mut state = State::new_temp();
state.add_balance(&sender, &U256::from(100));
let info = EnvInfo::new();
let engine = TestEngine::new(1024);
let engine = TestEngine::new(1024, factory);
let mut substate = Substate::new();
{
@ -529,9 +551,8 @@ mod tests {
}
// test is incorrect, mk
#[ignore]
#[test]
fn test_aba_calls() {
evm_test_ignore!{test_aba_calls: test_aba_calls_jit, test_aba_calls_int}
fn test_aba_calls(factory: Factory) {
// 60 00 - push 0
// 60 00 - push 0
// 60 00 - push 0
@ -576,7 +597,7 @@ mod tests {
state.add_balance(&sender, &U256::from(100_000));
let info = EnvInfo::new();
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let gas_left = {
@ -589,9 +610,8 @@ mod tests {
}
// test is incorrect, mk
#[ignore]
#[test]
fn test_recursive_bomb1() {
evm_test_ignore!{test_recursive_bomb1: test_recursive_bomb1_jit, test_recursive_bomb1_int}
fn test_recursive_bomb1(factory: Factory) {
// 60 01 - push 1
// 60 00 - push 0
// 54 - sload
@ -620,7 +640,7 @@ mod tests {
let mut state = State::new_temp();
state.init_code(&address, code.clone());
let info = EnvInfo::new();
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let gas_left = {
@ -634,9 +654,8 @@ mod tests {
}
// test is incorrect, mk
#[ignore]
#[test]
fn test_transact_simple() {
evm_test_ignore!{test_transact_simple: test_transact_simple_jit, test_transact_simple_int}
fn test_transact_simple(factory: Factory) {
let mut t = Transaction::new_create(U256::from(17), "3331600055".from_hex().unwrap(), U256::from(100_000), U256::zero(), U256::zero());
let keypair = KeyPair::create().unwrap();
t.sign(&keypair.secret());
@ -647,7 +666,7 @@ mod tests {
state.add_balance(&sender, &U256::from(18));
let mut info = EnvInfo::new();
info.gas_limit = U256::from(100_000);
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let executed = {
let mut ex = Executive::new(&mut state, &info, &engine);
@ -666,14 +685,14 @@ mod tests {
assert_eq!(state.storage_at(&contract, &H256::new()), H256::from(&U256::from(1)));
}
#[test]
fn test_transact_invalid_sender() {
evm_test!{test_transact_invalid_sender: test_transact_invalid_sender_jit, test_transact_invalid_sender_int}
fn test_transact_invalid_sender(factory: Factory) {
let t = Transaction::new_create(U256::from(17), "3331600055".from_hex().unwrap(), U256::from(100_000), U256::zero(), U256::zero());
let mut state = State::new_temp();
let mut info = EnvInfo::new();
info.gas_limit = U256::from(100_000);
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
@ -686,8 +705,8 @@ mod tests {
}
}
#[test]
fn test_transact_invalid_nonce() {
evm_test!{test_transact_invalid_nonce: test_transact_invalid_nonce_jit, test_transact_invalid_nonce_int}
fn test_transact_invalid_nonce(factory: Factory) {
let mut t = Transaction::new_create(U256::from(17), "3331600055".from_hex().unwrap(), U256::from(100_000), U256::zero(), U256::one());
let keypair = KeyPair::create().unwrap();
t.sign(&keypair.secret());
@ -697,7 +716,7 @@ mod tests {
state.add_balance(&sender, &U256::from(17));
let mut info = EnvInfo::new();
info.gas_limit = U256::from(100_000);
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
@ -711,8 +730,8 @@ mod tests {
}
}
#[test]
fn test_transact_gas_limit_reached() {
evm_test!{test_transact_gas_limit_reached: test_transact_gas_limit_reached_jit, test_transact_gas_limit_reached_int}
fn test_transact_gas_limit_reached(factory: Factory) {
let mut t = Transaction::new_create(U256::from(17), "3331600055".from_hex().unwrap(), U256::from(80_001), U256::zero(), U256::zero());
let keypair = KeyPair::create().unwrap();
t.sign(&keypair.secret());
@ -723,7 +742,7 @@ mod tests {
let mut info = EnvInfo::new();
info.gas_used = U256::from(20_000);
info.gas_limit = U256::from(100_000);
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
@ -737,8 +756,8 @@ mod tests {
}
}
#[test]
fn test_not_enough_cash() {
evm_test!{test_not_enough_cash: test_not_enough_cash_jit, test_not_enough_cash_int}
fn test_not_enough_cash(factory: Factory) {
let mut t = Transaction::new_create(U256::from(18), "3331600055".from_hex().unwrap(), U256::from(100_000), U256::one(), U256::zero());
let keypair = KeyPair::create().unwrap();
t.sign(&keypair.secret());
@ -748,7 +767,7 @@ mod tests {
state.add_balance(&sender, &U256::from(100_017));
let mut info = EnvInfo::new();
info.gas_limit = U256::from(100_000);
let engine = TestEngine::new(0);
let engine = TestEngine::new(0, factory);
let res = {
let mut ex = Executive::new(&mut state, &info, &engine);
@ -761,4 +780,40 @@ mod tests {
_ => assert!(false, "Expected not enough cash error. {:?}", res)
}
}
evm_test!{test_sha3: test_sha3_jit, test_sha3_int}
fn test_sha3(factory: Factory) {
let code = "6064640fffffffff20600055".from_hex().unwrap();
let sender = Address::from_str("0f572e5295c57f15886f9b263e2f6d2d6c7b5ec6").unwrap();
let address = contract_address(&sender, &U256::zero());
// TODO: add tests for 'callcreate'
//let next_address = contract_address(&address, &U256::zero());
let mut params = ActionParams::new();
params.address = address.clone();
params.sender = sender.clone();
params.origin = sender.clone();
params.gas = U256::from(0x0186a0);
params.code = Some(code.clone());
params.value = U256::from_str("0de0b6b3a7640000").unwrap();
let mut state = State::new_temp();
state.add_balance(&sender, &U256::from_str("152d02c7e14af6800000").unwrap());
let info = EnvInfo::new();
let engine = TestEngine::new(0, factory);
let mut substate = Substate::new();
let result = {
let mut ex = Executive::new(&mut state, &info, &engine);
ex.create(params, &mut substate)
};
match result {
Err(_) => {
},
_ => {
panic!("Expected OutOfGas");
}
}
}
}

View File

@ -157,7 +157,7 @@ impl<'a> Ext for Externalities<'a> {
}
}
fn extcode(&self, address: &Address) -> Vec<u8> {
fn extcode(&self, address: &Address) -> Bytes {
self.state.code(address).unwrap_or(vec![])
}
@ -196,9 +196,9 @@ impl<'a> Ext for Externalities<'a> {
}
}
fn log(&mut self, topics: Vec<H256>, data: Bytes) {
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
let address = self.origin_info.address.clone();
self.substate.logs.push(LogEntry::new(address, topics, data));
self.substate.logs.push(LogEntry::new(address, topics, data.to_vec()));
}
fn suicide(&mut self, refund_address: &Address) {

View File

@ -1,5 +1,6 @@
#![feature(cell_extras)]
#![feature(augmented_assignments)]
#![feature(wrapping)]
//#![feature(plugin)]
//#![plugin(interpolate_idents)]
//! Ethcore's ethereum implementation
@ -89,6 +90,8 @@ extern crate ethcore_util as util;
pub mod common;
pub mod basic_types;
#[macro_use]
pub mod evm;
pub mod error;
pub mod log_entry;
pub mod env_info;
@ -110,7 +113,6 @@ pub mod views;
pub mod blockchain;
pub mod extras;
pub mod substate;
pub mod evm;
pub mod service;
pub mod executive;
pub mod externalities;

View File

@ -1,20 +1,29 @@
use engine::Engine;
use spec::Spec;
use evm::Schedule;
use evm::Factory;
use env_info::EnvInfo;
/// An engine which does not provide any consensus mechanism.
pub struct NullEngine {
spec: Spec,
factory: Factory
}
impl NullEngine {
pub fn new_boxed(spec: Spec) -> Box<Engine> {
Box::new(NullEngine{spec: spec})
Box::new(NullEngine{
spec: spec,
// TODO [todr] should this return any specific factory?
factory: Factory::default()
})
}
}
impl Engine for NullEngine {
fn vm_factory(&self) -> &Factory {
&self.factory
}
fn name(&self) -> &str { "NullEngine" }
fn spec(&self) -> &Spec { &self.spec }
fn schedule(&self, _env_info: &EnvInfo) -> Schedule { Schedule::new_frontier() }

View File

@ -101,7 +101,7 @@ impl State {
}
/// Mutate storage of account `a` so that it is `value` for `key`.
pub fn code(&self, a: &Address) -> Option<Vec<u8>> {
pub fn code(&self, a: &Address) -> Option<Bytes> {
self.get(a, true).as_ref().map(|a|a.code().map(|x|x.to_vec())).unwrap_or(None)
}

View File

@ -4,19 +4,21 @@ use executive::*;
use spec::*;
use engine::*;
use evm;
use evm::{Schedule, Ext, Factory, ContractCreateResult, MessageCallResult};
use evm::{Schedule, Ext, Factory, VMType, ContractCreateResult, MessageCallResult};
use ethereum;
use externalities::*;
use substate::*;
struct TestEngine {
vm_factory: Factory,
spec: Spec,
max_depth: usize
}
impl TestEngine {
fn new(max_depth: usize) -> TestEngine {
fn new(max_depth: usize, vm_type: VMType) -> TestEngine {
TestEngine {
vm_factory: Factory::new(vm_type),
spec: ethereum::new_frontier_test(),
max_depth: max_depth
}
@ -26,6 +28,7 @@ impl TestEngine {
impl Engine for TestEngine {
fn name(&self) -> &str { "TestEngine" }
fn spec(&self) -> &Spec { &self.spec }
fn vm_factory(&self) -> &Factory { &self.vm_factory }
fn schedule(&self, _env_info: &EnvInfo) -> Schedule {
let mut schedule = Schedule::new_frontier();
schedule.max_depth = self.max_depth;
@ -112,11 +115,11 @@ impl<'a> Ext for TestExt<'a> {
MessageCallResult::Success(*gas)
}
fn extcode(&self, address: &Address) -> Vec<u8> {
fn extcode(&self, address: &Address) -> Bytes {
self.ext.extcode(address)
}
fn log(&mut self, topics: Vec<H256>, data: Bytes) {
fn log(&mut self, topics: Vec<H256>, data: &[u8]) {
self.ext.log(topics, data)
}
@ -146,17 +149,28 @@ impl<'a> Ext for TestExt<'a> {
}
fn do_json_test(json_data: &[u8]) -> Vec<String> {
let vms = VMType::all();
vms
.iter()
.flat_map(|vm| do_json_test_for(vm, json_data))
.collect()
}
fn do_json_test_for(vm: &VMType, json_data: &[u8]) -> Vec<String> {
let json = Json::from_str(::std::str::from_utf8(json_data).unwrap()).expect("Json is invalid");
let mut failed = Vec::new();
for (name, test) in json.as_object().unwrap() {
println!("name: {:?}", name);
// sync io is usefull when something crashes in jit
//::std::io::stdout().write(&name.as_bytes());
//::std::io::stdout().write(b"\n");
//::std::io::stdout().flush();
// ::std::io::stdout().write(&name.as_bytes());
// ::std::io::stdout().write(b"\n");
// ::std::io::stdout().flush();
let mut fail = false;
//let mut fail_unless = |cond: bool| if !cond && !fail { failed.push(name.to_string()); fail = true };
let mut fail_unless = |cond: bool, s: &str | if !cond && !fail { failed.push(name.to_string() + ": "+ s); fail = true };
let mut fail_unless = |cond: bool, s: &str | if !cond && !fail {
failed.push(format!("[{}] {}: {}", vm, name.to_string(), s));
fail = true
};
// test env
let mut state = State::new_temp();
@ -183,7 +197,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
info.timestamp = xjson!(&env["currentTimestamp"]);
});
let engine = TestEngine::new(1);
let engine = TestEngine::new(1, vm.clone());
// params
let mut params = ActionParams::new();
@ -214,7 +228,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
&mut substate,
OutputPolicy::Return(BytesRef::Flexible(&mut output)),
params.address.clone());
let evm = Factory::create();
let evm = engine.vm_factory().create();
let res = evm.exec(params, &mut ex);
(res, ex.callcreates)
};
@ -223,7 +237,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
match res {
Err(_) => fail_unless(out_of_gas, "didn't expect to run out of gas."),
Ok(gas_left) => {
//println!("name: {}, gas_left : {:?}, expected: {:?}", name, gas_left, U256::from(&test["gas"]));
// println!("name: {}, gas_left : {:?}", name, gas_left);
fail_unless(!out_of_gas, "expected to run out of gas.");
fail_unless(gas_left == xjson!(&test["gas"]), "gas_left is incorrect");
fail_unless(output == Bytes::from_json(&test["out"]), "output is incorrect");

View File

@ -8,8 +8,7 @@ fn do_json_test(json_data: &[u8]) -> Vec<String> {
let json = Json::from_str(::std::str::from_utf8(json_data).unwrap()).expect("Json is invalid");
let mut failed = Vec::new();
let engine = ethereum::new_frontier_test().to_engine().unwrap();
let engine = ethereum::new_frontier_like_test().to_engine().unwrap();
flush(format!("\n"));
for (name, test) in json.as_object().unwrap() {