From 20c742e47406c13ebc6427951f6fcf1b0056ea26 Mon Sep 17 00:00:00 2001 From: obscuren Date: Sat, 18 Oct 2014 13:31:20 +0200 Subject: Moved ethvm => vm --- vm/.ethtest | 0 vm/address.go | 42 +++ vm/asm.go | 45 +++ vm/closure.go | 140 ++++++++ vm/common.go | 66 ++++ vm/debugger.go | 10 + vm/environment.go | 26 ++ vm/execution.go | 93 +++++ vm/stack.go | 162 +++++++++ vm/types.go | 314 +++++++++++++++++ vm/virtual_machine.go | 9 + vm/vm.go | 724 +++++++++++++++++++++++++++++++++++++++ vm/vm_debug.go | 922 ++++++++++++++++++++++++++++++++++++++++++++++++++ vm/vm_test.go | 155 +++++++++ 14 files changed, 2708 insertions(+) create mode 100644 vm/.ethtest create mode 100644 vm/address.go create mode 100644 vm/asm.go create mode 100644 vm/closure.go create mode 100644 vm/common.go create mode 100644 vm/debugger.go create mode 100644 vm/environment.go create mode 100644 vm/execution.go create mode 100644 vm/stack.go create mode 100644 vm/types.go create mode 100644 vm/virtual_machine.go create mode 100644 vm/vm.go create mode 100644 vm/vm_debug.go create mode 100644 vm/vm_test.go (limited to 'vm') diff --git a/vm/.ethtest b/vm/.ethtest new file mode 100644 index 000000000..e69de29bb diff --git a/vm/address.go b/vm/address.go new file mode 100644 index 000000000..cfb7f36d9 --- /dev/null +++ b/vm/address.go @@ -0,0 +1,42 @@ +package vm + +import ( + "math/big" + + "github.com/ethereum/eth-go/ethcrypto" + "github.com/ethereum/eth-go/ethutil" +) + +type Address interface { + Call(in []byte) []byte +} + +type PrecompiledAddress struct { + Gas *big.Int + fn func(in []byte) []byte +} + +func (self PrecompiledAddress) Call(in []byte) []byte { + return self.fn(in) +} + +var Precompiled = map[uint64]*PrecompiledAddress{ + 1: &PrecompiledAddress{big.NewInt(500), ecrecoverFunc}, + 2: &PrecompiledAddress{big.NewInt(100), sha256Func}, + 3: &PrecompiledAddress{big.NewInt(100), ripemd160Func}, +} + +func sha256Func(in []byte) []byte { + return ethcrypto.Sha256(in) +} + +func ripemd160Func(in []byte) []byte { + return ethutil.RightPadBytes(ethcrypto.Ripemd160(in), 32) +} + +func ecrecoverFunc(in []byte) []byte { + // In case of an invalid sig. Defaults to return nil + defer func() { recover() }() + + return ethcrypto.Ecrecover(in) +} diff --git a/vm/asm.go b/vm/asm.go new file mode 100644 index 000000000..d081e2b09 --- /dev/null +++ b/vm/asm.go @@ -0,0 +1,45 @@ +package vm + +import ( + "fmt" + "math/big" + + "github.com/ethereum/eth-go/ethutil" +) + +func Disassemble(script []byte) (asm []string) { + pc := new(big.Int) + for { + if pc.Cmp(big.NewInt(int64(len(script)))) >= 0 { + return + } + + // Get the memory location of pc + val := script[pc.Int64()] + // Get the opcode (it must be an opcode!) + op := OpCode(val) + + asm = append(asm, fmt.Sprintf("%v", op)) + + switch op { + case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32: + pc.Add(pc, ethutil.Big1) + a := int64(op) - int64(PUSH1) + 1 + if int(pc.Int64()+a) > len(script) { + return nil + } + + data := script[pc.Int64() : pc.Int64()+a] + if len(data) == 0 { + data = []byte{0} + } + asm = append(asm, fmt.Sprintf("0x%x", data)) + + pc.Add(pc, big.NewInt(a-1)) + } + + pc.Add(pc, ethutil.Big1) + } + + return +} diff --git a/vm/closure.go b/vm/closure.go new file mode 100644 index 000000000..5a1e1d4d5 --- /dev/null +++ b/vm/closure.go @@ -0,0 +1,140 @@ +package vm + +// TODO Re write VM to use values instead of big integers? + +import ( + "math/big" + + "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/ethutil" +) + +type ClosureRef interface { + ReturnGas(*big.Int, *big.Int) + Address() []byte + Object() *ethstate.StateObject + GetStorage(*big.Int) *ethutil.Value + SetStorage(*big.Int, *ethutil.Value) +} + +// Basic inline closure object which implement the 'closure' interface +type Closure struct { + caller ClosureRef + object *ethstate.StateObject + Code []byte + message *ethstate.Message + exe *Execution + + Gas, UsedGas, Price *big.Int + + Args []byte +} + +// Create a new closure for the given data items +func NewClosure(msg *ethstate.Message, caller ClosureRef, object *ethstate.StateObject, code []byte, gas, price *big.Int) *Closure { + c := &Closure{message: msg, caller: caller, object: object, Code: code, Args: nil} + + // Gas should be a pointer so it can safely be reduced through the run + // This pointer will be off the state transition + c.Gas = gas //new(big.Int).Set(gas) + // In most cases price and value are pointers to transaction objects + // and we don't want the transaction's values to change. + c.Price = new(big.Int).Set(price) + c.UsedGas = new(big.Int) + + return c +} + +// Retuns the x element in data slice +func (c *Closure) GetStorage(x *big.Int) *ethutil.Value { + m := c.object.GetStorage(x) + if m == nil { + return ethutil.EmptyValue() + } + + return m +} + +func (c *Closure) Get(x *big.Int) *ethutil.Value { + return c.Gets(x, big.NewInt(1)) +} + +func (c *Closure) GetOp(x int) OpCode { + return OpCode(c.GetByte(x)) +} + +func (c *Closure) GetByte(x int) byte { + if x < len(c.Code) { + return c.Code[x] + } + + return 0 +} + +func (c *Closure) GetBytes(x, y int) []byte { + if x >= len(c.Code) || y >= len(c.Code) { + return nil + } + + return c.Code[x : x+y] +} + +func (c *Closure) Gets(x, y *big.Int) *ethutil.Value { + if x.Int64() >= int64(len(c.Code)) || y.Int64() >= int64(len(c.Code)) { + return ethutil.NewValue(0) + } + + partial := c.Code[x.Int64() : x.Int64()+y.Int64()] + + return ethutil.NewValue(partial) +} + +func (c *Closure) SetStorage(x *big.Int, val *ethutil.Value) { + c.object.SetStorage(x, val) +} + +func (c *Closure) Address() []byte { + return c.object.Address() +} + +func (c *Closure) Call(vm VirtualMachine, args []byte) ([]byte, *big.Int, error) { + c.Args = args + + ret, err := vm.RunClosure(c) + + return ret, c.UsedGas, err +} + +func (c *Closure) Return(ret []byte) []byte { + // Return the remaining gas to the caller + c.caller.ReturnGas(c.Gas, c.Price) + + return ret +} + +func (c *Closure) UseGas(gas *big.Int) bool { + if c.Gas.Cmp(gas) < 0 { + return false + } + + // Sub the amount of gas from the remaining + c.Gas.Sub(c.Gas, gas) + c.UsedGas.Add(c.UsedGas, gas) + + return true +} + +// Implement the caller interface +func (c *Closure) ReturnGas(gas, price *big.Int) { + // Return the gas to the closure + c.Gas.Add(c.Gas, gas) + c.UsedGas.Sub(c.UsedGas, gas) +} + +func (c *Closure) Object() *ethstate.StateObject { + return c.object +} + +func (c *Closure) Caller() ClosureRef { + return c.caller +} diff --git a/vm/common.go b/vm/common.go new file mode 100644 index 000000000..6921b38ff --- /dev/null +++ b/vm/common.go @@ -0,0 +1,66 @@ +package vm + +import ( + "math/big" + + "github.com/ethereum/eth-go/ethlog" + "github.com/ethereum/eth-go/ethutil" +) + +var vmlogger = ethlog.NewLogger("VM") + +type Type int + +const ( + StandardVmTy Type = iota + DebugVmTy + + MaxVmTy +) + +var ( + GasStep = big.NewInt(1) + GasSha = big.NewInt(20) + GasSLoad = big.NewInt(20) + GasSStore = big.NewInt(100) + GasBalance = big.NewInt(20) + GasCreate = big.NewInt(100) + GasCall = big.NewInt(20) + GasMemory = big.NewInt(1) + GasData = big.NewInt(5) + GasTx = big.NewInt(500) + + Pow256 = ethutil.BigPow(2, 256) + + LogTyPretty byte = 0x1 + LogTyDiff byte = 0x2 + + U256 = ethutil.U256 + S256 = ethutil.S256 +) + +const MaxCallDepth = 1024 + +func calcMemSize(off, l *big.Int) *big.Int { + if l.Cmp(ethutil.Big0) == 0 { + return ethutil.Big0 + } + + return new(big.Int).Add(off, l) +} + +// Simple helper +func u256(n int64) *big.Int { + return big.NewInt(n) +} + +// Mainly used for print variables and passing to Print* +func toValue(val *big.Int) interface{} { + // Let's assume a string on right padded zero's + b := val.Bytes() + if b[0] != 0 && b[len(b)-1] == 0x0 && b[len(b)-2] == 0x0 { + return string(b) + } + + return val +} diff --git a/vm/debugger.go b/vm/debugger.go new file mode 100644 index 000000000..fdd5e34e2 --- /dev/null +++ b/vm/debugger.go @@ -0,0 +1,10 @@ +package vm + +import "github.com/ethereum/eth-go/ethstate" + +type Debugger interface { + BreakHook(step int, op OpCode, mem *Memory, stack *Stack, object *ethstate.StateObject) bool + StepHook(step int, op OpCode, mem *Memory, stack *Stack, object *ethstate.StateObject) bool + BreakPoints() []int64 + SetCode(byteCode []byte) +} diff --git a/vm/environment.go b/vm/environment.go new file mode 100644 index 000000000..2d933b65c --- /dev/null +++ b/vm/environment.go @@ -0,0 +1,26 @@ +package vm + +import ( + "math/big" + + "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/ethutil" +) + +type Environment interface { + State() *ethstate.State + + Origin() []byte + BlockNumber() *big.Int + PrevHash() []byte + Coinbase() []byte + Time() int64 + Difficulty() *big.Int + BlockHash() []byte + GasLimit() *big.Int +} + +type Object interface { + GetStorage(key *big.Int) *ethutil.Value + SetStorage(key *big.Int, value *ethutil.Value) +} diff --git a/vm/execution.go b/vm/execution.go new file mode 100644 index 000000000..6bed43026 --- /dev/null +++ b/vm/execution.go @@ -0,0 +1,93 @@ +package vm + +import ( + "fmt" + "math/big" + + "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/ethutil" +) + +type Execution struct { + vm VirtualMachine + address, input []byte + Gas, price, value *big.Int + object *ethstate.StateObject +} + +func NewExecution(vm VirtualMachine, address, input []byte, gas, gasPrice, value *big.Int) *Execution { + return &Execution{vm: vm, address: address, input: input, Gas: gas, price: gasPrice, value: value} +} + +func (self *Execution) Addr() []byte { + return self.address +} + +func (self *Execution) Exec(codeAddr []byte, caller ClosureRef) ([]byte, error) { + // Retrieve the executing code + code := self.vm.Env().State().GetCode(codeAddr) + + return self.exec(code, codeAddr, caller) +} + +func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, err error) { + env := self.vm.Env() + + snapshot := env.State().Copy() + defer func() { + if err != nil { + env.State().Set(snapshot) + } + }() + + msg := env.State().Manifest().AddMessage(ðstate.Message{ + To: self.address, From: caller.Address(), + Input: self.input, + Origin: env.Origin(), + Block: env.BlockHash(), Timestamp: env.Time(), Coinbase: env.Coinbase(), Number: env.BlockNumber(), + Value: self.value, + }) + + object := caller.Object() + if object.Balance.Cmp(self.value) < 0 { + caller.ReturnGas(self.Gas, self.price) + + err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, object.Balance) + } else { + stateObject := env.State().GetOrNewStateObject(self.address) + self.object = stateObject + + caller.Object().SubAmount(self.value) + stateObject.AddAmount(self.value) + + // Pre-compiled contracts (address.go) 1, 2 & 3. + naddr := ethutil.BigD(caddr).Uint64() + if p := Precompiled[naddr]; p != nil { + if self.Gas.Cmp(p.Gas) >= 0 { + ret = p.Call(self.input) + self.vm.Printf("NATIVE_FUNC(%x) => %x", naddr, ret) + } + } else { + // Create a new callable closure + c := NewClosure(msg, caller, stateObject, code, self.Gas, self.price) + c.exe = self + + if self.vm.Depth() == MaxCallDepth { + c.UseGas(c.Gas) + + return c.Return(nil), fmt.Errorf("Max call depth exceeded (%d)", MaxCallDepth) + } + + // Executer the closure and get the return value (if any) + ret, _, err = c.Call(self.vm, self.input) + + msg.Output = ret + } + } + + return +} + +func (self *Execution) Create(caller ClosureRef) (ret []byte, err error) { + return self.exec(self.input, nil, caller) +} diff --git a/vm/stack.go b/vm/stack.go new file mode 100644 index 000000000..55fdb6d15 --- /dev/null +++ b/vm/stack.go @@ -0,0 +1,162 @@ +package vm + +import ( + "fmt" + "math" + "math/big" +) + +type OpType int + +const ( + tNorm = iota + tData + tExtro + tCrypto +) + +type TxCallback func(opType OpType) bool + +// Simple push/pop stack mechanism +type Stack struct { + data []*big.Int +} + +func NewStack() *Stack { + return &Stack{} +} + +func (st *Stack) Data() []*big.Int { + return st.data +} + +func (st *Stack) Len() int { + return len(st.data) +} + +func (st *Stack) Pop() *big.Int { + str := st.data[len(st.data)-1] + + copy(st.data[:len(st.data)-1], st.data[:len(st.data)-1]) + st.data = st.data[:len(st.data)-1] + + return str +} + +func (st *Stack) Popn() (*big.Int, *big.Int) { + ints := st.data[len(st.data)-2:] + + copy(st.data[:len(st.data)-2], st.data[:len(st.data)-2]) + st.data = st.data[:len(st.data)-2] + + return ints[0], ints[1] +} + +func (st *Stack) Peek() *big.Int { + str := st.data[len(st.data)-1] + + return str +} + +func (st *Stack) Peekn() (*big.Int, *big.Int) { + ints := st.data[len(st.data)-2:] + + return ints[0], ints[1] +} + +func (st *Stack) Swapn(n int) (*big.Int, *big.Int) { + st.data[len(st.data)-n], st.data[len(st.data)-1] = st.data[len(st.data)-1], st.data[len(st.data)-n] + + return st.data[len(st.data)-n], st.data[len(st.data)-1] +} + +func (st *Stack) Dupn(n int) *big.Int { + st.Push(st.data[len(st.data)-n]) + + return st.Peek() +} + +func (st *Stack) Push(d *big.Int) { + st.data = append(st.data, new(big.Int).Set(d)) +} + +func (st *Stack) Get(amount *big.Int) []*big.Int { + // offset + size <= len(data) + length := big.NewInt(int64(len(st.data))) + if amount.Cmp(length) <= 0 { + start := new(big.Int).Sub(length, amount) + return st.data[start.Int64():length.Int64()] + } + + return nil +} + +func (st *Stack) Print() { + fmt.Println("### stack ###") + if len(st.data) > 0 { + for i, val := range st.data { + fmt.Printf("%-3d %v\n", i, val) + } + } else { + fmt.Println("-- empty --") + } + fmt.Println("#############") +} + +type Memory struct { + store []byte +} + +func (m *Memory) Set(offset, size int64, value []byte) { + totSize := offset + size + lenSize := int64(len(m.store) - 1) + if totSize > lenSize { + // Calculate the diff between the sizes + diff := totSize - lenSize + if diff > 0 { + // Create a new empty slice and append it + newSlice := make([]byte, diff-1) + // Resize slice + m.store = append(m.store, newSlice...) + } + } + copy(m.store[offset:offset+size], value) +} + +func (m *Memory) Resize(size uint64) { + if uint64(m.Len()) < size { + m.store = append(m.store, make([]byte, size-uint64(m.Len()))...) + } +} + +func (m *Memory) Get(offset, size int64) []byte { + if len(m.store) > int(offset) { + end := int(math.Min(float64(len(m.store)), float64(offset+size))) + + return m.store[offset:end] + } + + return nil +} + +func (m *Memory) Len() int { + return len(m.store) +} + +func (m *Memory) Data() []byte { + return m.store +} + +func (m *Memory) Print() { + fmt.Printf("### mem %d bytes ###\n", len(m.store)) + if len(m.store) > 0 { + addr := 0 + for i := 0; i+32 <= len(m.store); i += 32 { + fmt.Printf("%03d: % x\n", addr, m.store[i:i+32]) + addr++ + } + } else { + fmt.Println("-- empty --") + } + fmt.Println("####################") +} diff --git a/vm/types.go b/vm/types.go new file mode 100644 index 000000000..5fd92052b --- /dev/null +++ b/vm/types.go @@ -0,0 +1,314 @@ +package vm + +import ( + "fmt" +) + +type OpCode byte + +// Op codes +const ( + // 0x0 range - arithmetic ops + STOP = 0x00 + ADD = 0x01 + MUL = 0x02 + SUB = 0x03 + DIV = 0x04 + SDIV = 0x05 + MOD = 0x06 + SMOD = 0x07 + EXP = 0x08 + NEG = 0x09 + LT = 0x0a + GT = 0x0b + SLT = 0x0c + SGT = 0x0d + EQ = 0x0e + NOT = 0x0f + + // 0x10 range - bit ops + AND = 0x10 + OR = 0x11 + XOR = 0x12 + BYTE = 0x13 + ADDMOD = 0x14 + MULMOD = 0x15 + + // 0x20 range - crypto + SHA3 = 0x20 + + // 0x30 range - closure state + ADDRESS = 0x30 + BALANCE = 0x31 + ORIGIN = 0x32 + CALLER = 0x33 + CALLVALUE = 0x34 + CALLDATALOAD = 0x35 + CALLDATASIZE = 0x36 + CALLDATACOPY = 0x37 + CODESIZE = 0x38 + CODECOPY = 0x39 + GASPRICE = 0x3a + EXTCODESIZE = 0x3b + EXTCODECOPY = 0x3c + + // 0x40 range - block operations + PREVHASH = 0x40 + COINBASE = 0x41 + TIMESTAMP = 0x42 + NUMBER = 0x43 + DIFFICULTY = 0x44 + GASLIMIT = 0x45 + + // 0x50 range - 'storage' and execution + POP = 0x50 + //DUP = 0x51 + //SWAP = 0x52 + MLOAD = 0x53 + MSTORE = 0x54 + MSTORE8 = 0x55 + SLOAD = 0x56 + SSTORE = 0x57 + JUMP = 0x58 + JUMPI = 0x59 + PC = 0x5a + MSIZE = 0x5b + GAS = 0x5c + JUMPDEST = 0x5d + + // 0x60 range + PUSH1 = 0x60 + PUSH2 = 0x61 + PUSH3 = 0x62 + PUSH4 = 0x63 + PUSH5 = 0x64 + PUSH6 = 0x65 + PUSH7 = 0x66 + PUSH8 = 0x67 + PUSH9 = 0x68 + PUSH10 = 0x69 + PUSH11 = 0x6a + PUSH12 = 0x6b + PUSH13 = 0x6c + PUSH14 = 0x6d + PUSH15 = 0x6e + PUSH16 = 0x6f + PUSH17 = 0x70 + PUSH18 = 0x71 + PUSH19 = 0x72 + PUSH20 = 0x73 + PUSH21 = 0x74 + PUSH22 = 0x75 + PUSH23 = 0x76 + PUSH24 = 0x77 + PUSH25 = 0x78 + PUSH26 = 0x79 + PUSH27 = 0x7a + PUSH28 = 0x7b + PUSH29 = 0x7c + PUSH30 = 0x7d + PUSH31 = 0x7e + PUSH32 = 0x7f + + DUP1 = 0x80 + DUP2 = 0x81 + DUP3 = 0x82 + DUP4 = 0x83 + DUP5 = 0x84 + DUP6 = 0x85 + DUP7 = 0x86 + DUP8 = 0x87 + DUP9 = 0x88 + DUP10 = 0x89 + DUP11 = 0x8a + DUP12 = 0x8b + DUP13 = 0x8c + DUP14 = 0x8d + DUP15 = 0x8e + DUP16 = 0x8f + + SWAP1 = 0x90 + SWAP2 = 0x91 + SWAP3 = 0x92 + SWAP4 = 0x93 + SWAP5 = 0x94 + SWAP6 = 0x95 + SWAP7 = 0x96 + SWAP8 = 0x97 + SWAP9 = 0x98 + SWAP10 = 0x99 + SWAP11 = 0x9a + SWAP12 = 0x9b + SWAP13 = 0x9c + SWAP14 = 0x9d + SWAP15 = 0x9e + SWAP16 = 0x9f + + // 0xf0 range - closures + CREATE = 0xf0 + CALL = 0xf1 + RETURN = 0xf2 + CALLCODE = 0xf3 + + // 0x70 range - other + LOG = 0xfe // XXX Unofficial + SUICIDE = 0xff +) + +// Since the opcodes aren't all in order we can't use a regular slice +var opCodeToString = map[OpCode]string{ + // 0x0 range - arithmetic ops + STOP: "STOP", + ADD: "ADD", + MUL: "MUL", + SUB: "SUB", + DIV: "DIV", + SDIV: "SDIV", + MOD: "MOD", + SMOD: "SMOD", + EXP: "EXP", + NEG: "NEG", + LT: "LT", + GT: "GT", + SLT: "SLT", + SGT: "SGT", + EQ: "EQ", + NOT: "NOT", + + // 0x10 range - bit ops + AND: "AND", + OR: "OR", + XOR: "XOR", + BYTE: "BYTE", + ADDMOD: "ADDMOD", + MULMOD: "MULMOD", + + // 0x20 range - crypto + SHA3: "SHA3", + + // 0x30 range - closure state + ADDRESS: "ADDRESS", + BALANCE: "BALANCE", + ORIGIN: "ORIGIN", + CALLER: "CALLER", + CALLVALUE: "CALLVALUE", + CALLDATALOAD: "CALLDATALOAD", + CALLDATASIZE: "CALLDATASIZE", + CALLDATACOPY: "CALLDATACOPY", + CODESIZE: "CODESIZE", + CODECOPY: "CODECOPY", + GASPRICE: "TXGASPRICE", + + // 0x40 range - block operations + PREVHASH: "PREVHASH", + COINBASE: "COINBASE", + TIMESTAMP: "TIMESTAMP", + NUMBER: "NUMBER", + DIFFICULTY: "DIFFICULTY", + GASLIMIT: "GASLIMIT", + EXTCODESIZE: "EXTCODESIZE", + EXTCODECOPY: "EXTCODECOPY", + + // 0x50 range - 'storage' and execution + POP: "POP", + //DUP: "DUP", + //SWAP: "SWAP", + MLOAD: "MLOAD", + MSTORE: "MSTORE", + MSTORE8: "MSTORE8", + SLOAD: "SLOAD", + SSTORE: "SSTORE", + JUMP: "JUMP", + JUMPI: "JUMPI", + PC: "PC", + MSIZE: "MSIZE", + GAS: "GAS", + JUMPDEST: "JUMPDEST", + + // 0x60 range - push + PUSH1: "PUSH1", + PUSH2: "PUSH2", + PUSH3: "PUSH3", + PUSH4: "PUSH4", + PUSH5: "PUSH5", + PUSH6: "PUSH6", + PUSH7: "PUSH7", + PUSH8: "PUSH8", + PUSH9: "PUSH9", + PUSH10: "PUSH10", + PUSH11: "PUSH11", + PUSH12: "PUSH12", + PUSH13: "PUSH13", + PUSH14: "PUSH14", + PUSH15: "PUSH15", + PUSH16: "PUSH16", + PUSH17: "PUSH17", + PUSH18: "PUSH18", + PUSH19: "PUSH19", + PUSH20: "PUSH20", + PUSH21: "PUSH21", + PUSH22: "PUSH22", + PUSH23: "PUSH23", + PUSH24: "PUSH24", + PUSH25: "PUSH25", + PUSH26: "PUSH26", + PUSH27: "PUSH27", + PUSH28: "PUSH28", + PUSH29: "PUSH29", + PUSH30: "PUSH30", + PUSH31: "PUSH31", + PUSH32: "PUSH32", + + DUP1: "DUP1", + DUP2: "DUP2", + DUP3: "DUP3", + DUP4: "DUP4", + DUP5: "DUP5", + DUP6: "DUP6", + DUP7: "DUP7", + DUP8: "DUP8", + DUP9: "DUP9", + DUP10: "DUP10", + DUP11: "DUP11", + DUP12: "DUP12", + DUP13: "DUP13", + DUP14: "DUP14", + DUP15: "DUP15", + DUP16: "DUP16", + + SWAP1: "SWAP1", + SWAP2: "SWAP2", + SWAP3: "SWAP3", + SWAP4: "SWAP4", + SWAP5: "SWAP5", + SWAP6: "SWAP6", + SWAP7: "SWAP7", + SWAP8: "SWAP8", + SWAP9: "SWAP9", + SWAP10: "SWAP10", + SWAP11: "SWAP11", + SWAP12: "SWAP12", + SWAP13: "SWAP13", + SWAP14: "SWAP14", + SWAP15: "SWAP15", + SWAP16: "SWAP16", + + // 0xf0 range + CREATE: "CREATE", + CALL: "CALL", + RETURN: "RETURN", + CALLCODE: "CALLCODE", + + // 0x70 range - other + LOG: "LOG", + SUICIDE: "SUICIDE", +} + +func (o OpCode) String() string { + str := opCodeToString[o] + if len(str) == 0 { + return fmt.Sprintf("Missing opcode 0x%x", int(o)) + } + + return str +} diff --git a/vm/virtual_machine.go b/vm/virtual_machine.go new file mode 100644 index 000000000..cc8cd39a9 --- /dev/null +++ b/vm/virtual_machine.go @@ -0,0 +1,9 @@ +package vm + +type VirtualMachine interface { + Env() Environment + RunClosure(*Closure) ([]byte, error) + Depth() int + Printf(string, ...interface{}) VirtualMachine + Endl() VirtualMachine +} diff --git a/vm/vm.go b/vm/vm.go new file mode 100644 index 000000000..72d4f7131 --- /dev/null +++ b/vm/vm.go @@ -0,0 +1,724 @@ +package vm + +import ( + "fmt" + "math/big" + + "github.com/ethereum/eth-go/ethcrypto" + "github.com/ethereum/eth-go/ethutil" +) + +// BIG FAT WARNING. THIS VM IS NOT YET IS USE! +// I want to get all VM tests pass first before updating this VM + +type Vm struct { + env Environment + err error + depth int +} + +func New(env Environment, typ Type) VirtualMachine { + switch typ { + case DebugVmTy: + return NewDebugVm(env) + default: + return &Vm{env: env} + } +} + +func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) { + self.depth++ + + // Recover from any require exception + defer func() { + if r := recover(); r != nil { + ret = closure.Return(nil) + err = fmt.Errorf("%v", r) + } + }() + + // Don't bother with the execution if there's no code. + if len(closure.Code) == 0 { + return closure.Return(nil), nil + } + + var ( + op OpCode + + mem = &Memory{} + stack = NewStack() + pc = 0 + step = 0 + require = func(m int) { + if stack.Len() < m { + panic(fmt.Sprintf("%04v (%v) stack err size = %d, required = %d", pc, op, stack.Len(), m)) + } + } + ) + + for { + // The base for all big integer arithmetic + base := new(big.Int) + + step++ + // Get the memory location of pc + op := closure.GetOp(pc) + + gas := new(big.Int) + addStepGasUsage := func(amount *big.Int) { + gas.Add(gas, amount) + } + + addStepGasUsage(GasStep) + + var newMemSize *big.Int = ethutil.Big0 + switch op { + case STOP: + gas.Set(ethutil.Big0) + case SUICIDE: + gas.Set(ethutil.Big0) + case SLOAD: + gas.Set(GasSLoad) + case SSTORE: + var mult *big.Int + y, x := stack.Peekn() + val := closure.GetStorage(x) + if val.BigInt().Cmp(ethutil.Big0) == 0 && len(y.Bytes()) > 0 { + mult = ethutil.Big2 + } else if val.BigInt().Cmp(ethutil.Big0) != 0 && len(y.Bytes()) == 0 { + mult = ethutil.Big0 + } else { + mult = ethutil.Big1 + } + gas = new(big.Int).Mul(mult, GasSStore) + case BALANCE: + gas.Set(GasBalance) + case MSTORE: + require(2) + newMemSize = calcMemSize(stack.Peek(), u256(32)) + case MLOAD: + require(1) + + newMemSize = calcMemSize(stack.Peek(), u256(32)) + case MSTORE8: + require(2) + newMemSize = calcMemSize(stack.Peek(), u256(1)) + case RETURN: + require(2) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2]) + case SHA3: + require(2) + + gas.Set(GasSha) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2]) + case CALLDATACOPY: + require(2) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3]) + case CODECOPY: + require(3) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3]) + case EXTCODECOPY: + require(4) + + newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-4]) + case CALL, CALLCODE: + require(7) + gas.Set(GasCall) + addStepGasUsage(stack.data[stack.Len()-1]) + + x := calcMemSize(stack.data[stack.Len()-6], stack.data[stack.Len()-7]) + y := calcMemSize(stack.data[stack.Len()-4], stack.data[stack.Len()-5]) + + newMemSize = ethutil.BigMax(x, y) + case CREATE: + require(3) + gas.Set(GasCreate) + + newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-3]) + } + + if newMemSize.Cmp(ethutil.Big0) > 0 { + newMemSize.Add(newMemSize, u256(31)) + newMemSize.Div(newMemSize, u256(32)) + newMemSize.Mul(newMemSize, u256(32)) + + if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 { + memGasUsage := new(big.Int).Sub(newMemSize, u256(int64(mem.Len()))) + memGasUsage.Mul(GasMemory, memGasUsage) + memGasUsage.Div(memGasUsage, u256(32)) + + addStepGasUsage(memGasUsage) + } + } + + if !closure.UseGas(gas) { + err := fmt.Errorf("Insufficient gas for %v. req %v has %v", op, gas, closure.Gas) + + closure.UseGas(closure.Gas) + + return closure.Return(nil), err + } + + mem.Resize(newMemSize.Uint64()) + + switch op { + // 0x20 range + case ADD: + require(2) + x, y := stack.Popn() + + base.Add(y, x) + + U256(base) + + // Pop result back on the stack + stack.Push(base) + case SUB: + require(2) + x, y := stack.Popn() + + base.Sub(y, x) + + U256(base) + + // Pop result back on the stack + stack.Push(base) + case MUL: + require(2) + x, y := stack.Popn() + + base.Mul(y, x) + + U256(base) + + // Pop result back on the stack + stack.Push(base) + case DIV: + require(2) + x, y := stack.Popn() + + if x.Cmp(ethutil.Big0) != 0 { + base.Div(y, x) + } + + U256(base) + + // Pop result back on the stack + stack.Push(base) + case SDIV: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + + if x.Cmp(ethutil.Big0) == 0 { + base.Set(ethutil.Big0) + } else { + n := new(big.Int) + if new(big.Int).Mul(y, x).Cmp(ethutil.Big0) < 0 { + n.SetInt64(-1) + } else { + n.SetInt64(1) + } + + base.Div(y.Abs(y), x.Mul(x.Abs(x), n)) + + U256(base) + } + + stack.Push(base) + case MOD: + require(2) + x, y := stack.Popn() + + base.Mod(y, x) + + U256(base) + + stack.Push(base) + case SMOD: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + + if x.Cmp(ethutil.Big0) == 0 { + base.Set(ethutil.Big0) + } else { + n := new(big.Int) + if y.Cmp(ethutil.Big0) < 0 { + n.SetInt64(-1) + } else { + n.SetInt64(1) + } + + base.Mod(y.Abs(y), x.Mul(x.Abs(x), n)) + + U256(base) + } + + stack.Push(base) + + case EXP: + require(2) + x, y := stack.Popn() + + base.Exp(y, x, Pow256) + + U256(base) + + stack.Push(base) + case NEG: + require(1) + base.Sub(Pow256, stack.Pop()) + + base = U256(base) + + stack.Push(base) + case LT: + require(2) + x, y := stack.Popn() + // x < y + if y.Cmp(x) < 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case GT: + require(2) + x, y := stack.Popn() + + // x > y + if y.Cmp(x) > 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + + case SLT: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + // x < y + if y.Cmp(S256(x)) < 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case SGT: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + + // x > y + if y.Cmp(x) > 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + + case EQ: + require(2) + x, y := stack.Popn() + + // x == y + if x.Cmp(y) == 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case NOT: + require(1) + x := stack.Pop() + if x.Cmp(ethutil.BigFalse) > 0 { + stack.Push(ethutil.BigFalse) + } else { + stack.Push(ethutil.BigTrue) + } + + // 0x10 range + case AND: + require(2) + x, y := stack.Popn() + + stack.Push(base.And(y, x)) + case OR: + require(2) + x, y := stack.Popn() + + stack.Push(base.Or(y, x)) + case XOR: + require(2) + x, y := stack.Popn() + + stack.Push(base.Xor(y, x)) + case BYTE: + require(2) + val, th := stack.Popn() + if th.Cmp(big.NewInt(32)) < 0 && th.Cmp(big.NewInt(int64(len(val.Bytes())))) < 0 { + byt := big.NewInt(int64(ethutil.LeftPadBytes(val.Bytes(), 32)[th.Int64()])) + stack.Push(byt) + + } else { + stack.Push(ethutil.BigFalse) + } + case ADDMOD: + require(3) + + x := stack.Pop() + y := stack.Pop() + z := stack.Pop() + + base.Add(x, y) + base.Mod(base, z) + + U256(base) + + stack.Push(base) + case MULMOD: + require(3) + + x := stack.Pop() + y := stack.Pop() + z := stack.Pop() + + base.Mul(x, y) + base.Mod(base, z) + + U256(base) + + stack.Push(base) + + // 0x20 range + case SHA3: + require(2) + size, offset := stack.Popn() + data := ethcrypto.Sha3(mem.Get(offset.Int64(), size.Int64())) + + stack.Push(ethutil.BigD(data)) + + // 0x30 range + case ADDRESS: + stack.Push(ethutil.BigD(closure.Address())) + + case BALANCE: + require(1) + + addr := stack.Pop().Bytes() + balance := self.env.State().GetBalance(addr) + + stack.Push(balance) + + case ORIGIN: + origin := self.env.Origin() + + stack.Push(ethutil.BigD(origin)) + + case CALLER: + caller := closure.caller.Address() + stack.Push(ethutil.BigD(caller)) + + case CALLVALUE: + value := closure.exe.value + + stack.Push(value) + + case CALLDATALOAD: + require(1) + var ( + offset = stack.Pop() + data = make([]byte, 32) + lenData = big.NewInt(int64(len(closure.Args))) + ) + + if lenData.Cmp(offset) >= 0 { + length := new(big.Int).Add(offset, ethutil.Big32) + length = ethutil.BigMin(length, lenData) + + copy(data, closure.Args[offset.Int64():length.Int64()]) + } + + stack.Push(ethutil.BigD(data)) + case CALLDATASIZE: + l := int64(len(closure.Args)) + stack.Push(big.NewInt(l)) + + case CALLDATACOPY: + var ( + size = int64(len(closure.Args)) + mOff = stack.Pop().Int64() + cOff = stack.Pop().Int64() + l = stack.Pop().Int64() + ) + + if cOff > size { + cOff = 0 + l = 0 + } else if cOff+l > size { + l = 0 + } + + code := closure.Args[cOff : cOff+l] + + mem.Set(mOff, l, code) + case CODESIZE, EXTCODESIZE: + var code []byte + if op == EXTCODECOPY { + addr := stack.Pop().Bytes() + + code = self.env.State().GetCode(addr) + } else { + code = closure.Code + } + + l := big.NewInt(int64(len(code))) + stack.Push(l) + + case CODECOPY, EXTCODECOPY: + var code []byte + if op == EXTCODECOPY { + addr := stack.Pop().Bytes() + + code = self.env.State().GetCode(addr) + } else { + code = closure.Code + } + + var ( + size = int64(len(code)) + mOff = stack.Pop().Int64() + cOff = stack.Pop().Int64() + l = stack.Pop().Int64() + ) + + if cOff > size { + cOff = 0 + l = 0 + } else if cOff+l > size { + l = 0 + } + + codeCopy := code[cOff : cOff+l] + + mem.Set(mOff, l, codeCopy) + case GASPRICE: + stack.Push(closure.Price) + + // 0x40 range + case PREVHASH: + prevHash := self.env.PrevHash() + + stack.Push(ethutil.BigD(prevHash)) + + case COINBASE: + coinbase := self.env.Coinbase() + + stack.Push(ethutil.BigD(coinbase)) + + case TIMESTAMP: + time := self.env.Time() + + stack.Push(big.NewInt(time)) + + case NUMBER: + number := self.env.BlockNumber() + + stack.Push(number) + + case DIFFICULTY: + difficulty := self.env.Difficulty() + + stack.Push(difficulty) + + case GASLIMIT: + // TODO + stack.Push(big.NewInt(0)) + + // 0x50 range + case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32: + a := int(op - PUSH1 + 1) + val := ethutil.BigD(closure.GetBytes(int(pc+1), a)) + // Push value to stack + stack.Push(val) + + pc += a + + step += int(op) - int(PUSH1) + 1 + case POP: + require(1) + stack.Pop() + case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16: + n := int(op - DUP1 + 1) + stack.Dupn(n) + case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16: + n := int(op - SWAP1 + 2) + stack.Swapn(n) + + case MLOAD: + require(1) + offset := stack.Pop() + val := ethutil.BigD(mem.Get(offset.Int64(), 32)) + stack.Push(val) + + case MSTORE: // Store the value at stack top-1 in to memory at location stack top + require(2) + // Pop value of the stack + val, mStart := stack.Popn() + mem.Set(mStart.Int64(), 32, ethutil.BigToBytes(val, 256)) + + case MSTORE8: + require(2) + off := stack.Pop() + val := stack.Pop() + + mem.store[off.Int64()] = byte(val.Int64() & 0xff) + + case SLOAD: + require(1) + loc := stack.Pop() + val := closure.GetStorage(loc) + + stack.Push(val.BigInt()) + + case SSTORE: + require(2) + val, loc := stack.Popn() + closure.SetStorage(loc, ethutil.NewValue(val)) + + closure.message.AddStorageChange(loc.Bytes()) + + case JUMP: + require(1) + pc = int(stack.Pop().Int64()) + // Reduce pc by one because of the increment that's at the end of this for loop + + continue + case JUMPI: + require(2) + cond, pos := stack.Popn() + if cond.Cmp(ethutil.BigTrue) >= 0 { + pc = int(pos.Int64()) + + if closure.GetOp(int(pc)) != JUMPDEST { + return closure.Return(nil), fmt.Errorf("JUMP missed JUMPDEST %v", pc) + } + + continue + } + case JUMPDEST: + case PC: + stack.Push(u256(int64(pc))) + case MSIZE: + stack.Push(big.NewInt(int64(mem.Len()))) + case GAS: + stack.Push(closure.Gas) + // 0x60 range + case CREATE: + require(3) + + var ( + err error + value = stack.Pop() + size, offset = stack.Popn() + input = mem.Get(offset.Int64(), size.Int64()) + gas = new(big.Int).Set(closure.Gas) + + // Snapshot the current stack so we are able to + // revert back to it later. + //snapshot = self.env.State().Copy() + ) + + // Generate a new address + addr := ethcrypto.CreateAddress(closure.Address(), closure.object.Nonce) + closure.object.Nonce++ + + closure.UseGas(closure.Gas) + + msg := NewExecution(self, addr, input, gas, closure.Price, value) + ret, err := msg.Exec(addr, closure) + if err != nil { + stack.Push(ethutil.BigFalse) + + // Revert the state as it was before. + //self.env.State().Set(snapshot) + + } else { + msg.object.Code = ret + + stack.Push(ethutil.BigD(addr)) + } + + case CALL, CALLCODE: + require(7) + + gas := stack.Pop() + // Pop gas and value of the stack. + value, addr := stack.Popn() + // Pop input size and offset + inSize, inOffset := stack.Popn() + // Pop return size and offset + retSize, retOffset := stack.Popn() + + // Get the arguments from the memory + args := mem.Get(inOffset.Int64(), inSize.Int64()) + + //snapshot := self.env.State().Copy() + + var executeAddr []byte + if op == CALLCODE { + executeAddr = closure.Address() + } else { + executeAddr = addr.Bytes() + } + + msg := NewExecution(self, executeAddr, args, gas, closure.Price, value) + ret, err := msg.Exec(addr.Bytes(), closure) + if err != nil { + stack.Push(ethutil.BigFalse) + + //self.env.State().Set(snapshot) + } else { + stack.Push(ethutil.BigTrue) + + mem.Set(retOffset.Int64(), retSize.Int64(), ret) + } + + case RETURN: + require(2) + size, offset := stack.Popn() + ret := mem.Get(offset.Int64(), size.Int64()) + + return closure.Return(ret), nil + case SUICIDE: + require(1) + + receiver := self.env.State().GetOrNewStateObject(stack.Pop().Bytes()) + + receiver.AddAmount(closure.object.Balance) + + closure.object.MarkForDeletion() + + fallthrough + case STOP: // Stop the closure + + return closure.Return(nil), nil + default: + vmlogger.Debugf("(pc) %-3v Invalid opcode %x\n", pc, op) + + //panic(fmt.Sprintf("Invalid opcode %x", op)) + + return closure.Return(nil), fmt.Errorf("Invalid opcode %x", op) + } + + pc++ + } +} + +func (self *Vm) Env() Environment { + return self.env +} + +func (self *Vm) Depth() int { + return self.depth +} + +func (self *Vm) Printf(format string, v ...interface{}) VirtualMachine { return self } +func (self *Vm) Endl() VirtualMachine { return self } diff --git a/vm/vm_debug.go b/vm/vm_debug.go new file mode 100644 index 000000000..785e699c7 --- /dev/null +++ b/vm/vm_debug.go @@ -0,0 +1,922 @@ +package vm + +import ( + "fmt" + "math/big" + + "github.com/ethereum/eth-go/ethcrypto" + "github.com/ethereum/eth-go/ethutil" +) + +type DebugVm struct { + env Environment + + logTy byte + logStr string + + err error + + // Debugging + Dbg Debugger + + BreakPoints []int64 + Stepping bool + Fn string + + Recoverable bool + + depth int +} + +func NewDebugVm(env Environment) *DebugVm { + lt := LogTyPretty + if ethutil.Config.Diff { + lt = LogTyDiff + } + + return &DebugVm{env: env, logTy: lt, Recoverable: true} +} + +func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { + self.depth++ + + var ( + op OpCode + + mem = &Memory{} + stack = NewStack() + pc = big.NewInt(0) + step = 0 + prevStep = 0 + state = self.env.State() + require = func(m int) { + if stack.Len() < m { + panic(fmt.Sprintf("%04v (%v) stack err size = %d, required = %d", pc, op, stack.Len(), m)) + } + } + + jump = func(pos *big.Int) { + p := int(pos.Int64()) + + self.Printf(" ~> %v", pos) + // Return to start + if p == 0 { + pc = big.NewInt(0) + } else { + nop := OpCode(closure.GetOp(p - 1)) + if nop != JUMPDEST { + panic(fmt.Sprintf("JUMP missed JUMPDEST (%v) %v", nop, p)) + } + + pc = pos + } + + self.Endl() + } + ) + + if self.Recoverable { + // Recover from any require exception + defer func() { + if r := recover(); r != nil { + self.Endl() + + ret = closure.Return(nil) + err = fmt.Errorf("%v", r) + } + }() + } + + // Debug hook + if self.Dbg != nil { + self.Dbg.SetCode(closure.Code) + } + + // Don't bother with the execution if there's no code. + if len(closure.Code) == 0 { + return closure.Return(nil), nil + } + + vmlogger.Debugf("(%s) %x gas: %v (d) %x\n", self.Fn, closure.Address(), closure.Gas, closure.Args) + + for { + prevStep = step + // The base for all big integer arithmetic + base := new(big.Int) + + step++ + // Get the memory location of pc + op := OpCode(closure.Get(pc).Uint()) + + // XXX Leave this Println intact. Don't change this to the log system. + // Used for creating diffs between implementations + if self.logTy == LogTyDiff { + switch op { + case STOP, RETURN, SUICIDE: + state.GetStateObject(closure.Address()).EachStorage(func(key string, value *ethutil.Value) { + value.Decode() + fmt.Printf("%x %x\n", new(big.Int).SetBytes([]byte(key)).Bytes(), value.Bytes()) + }) + } + + b := pc.Bytes() + if len(b) == 0 { + b = []byte{0} + } + + fmt.Printf("%x %x %x %x\n", closure.Address(), b, []byte{byte(op)}, closure.Gas.Bytes()) + } + + gas := new(big.Int) + addStepGasUsage := func(amount *big.Int) { + if amount.Cmp(ethutil.Big0) >= 0 { + gas.Add(gas, amount) + } + } + + addStepGasUsage(GasStep) + + var newMemSize *big.Int = ethutil.Big0 + switch op { + case STOP: + gas.Set(ethutil.Big0) + case SUICIDE: + gas.Set(ethutil.Big0) + case SLOAD: + gas.Set(GasSLoad) + case SSTORE: + var mult *big.Int + y, x := stack.Peekn() + val := closure.GetStorage(x) + if val.BigInt().Cmp(ethutil.Big0) == 0 && len(y.Bytes()) > 0 { + mult = ethutil.Big2 + } else if val.BigInt().Cmp(ethutil.Big0) != 0 && len(y.Bytes()) == 0 { + mult = ethutil.Big0 + } else { + mult = ethutil.Big1 + } + gas = new(big.Int).Mul(mult, GasSStore) + case BALANCE: + gas.Set(GasBalance) + case MSTORE: + require(2) + newMemSize = calcMemSize(stack.Peek(), u256(32)) + case MLOAD: + require(1) + + newMemSize = calcMemSize(stack.Peek(), u256(32)) + case MSTORE8: + require(2) + newMemSize = calcMemSize(stack.Peek(), u256(1)) + case RETURN: + require(2) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2]) + case SHA3: + require(2) + + gas.Set(GasSha) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-2]) + case CALLDATACOPY: + require(2) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3]) + case CODECOPY: + require(3) + + newMemSize = calcMemSize(stack.Peek(), stack.data[stack.Len()-3]) + case EXTCODECOPY: + require(4) + + newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-4]) + case CALL, CALLCODE: + require(7) + gas.Set(GasCall) + addStepGasUsage(stack.data[stack.Len()-1]) + + x := calcMemSize(stack.data[stack.Len()-6], stack.data[stack.Len()-7]) + y := calcMemSize(stack.data[stack.Len()-4], stack.data[stack.Len()-5]) + + newMemSize = ethutil.BigMax(x, y) + case CREATE: + require(3) + gas.Set(GasCreate) + + newMemSize = calcMemSize(stack.data[stack.Len()-2], stack.data[stack.Len()-3]) + } + + if newMemSize.Cmp(ethutil.Big0) > 0 { + newMemSize.Add(newMemSize, u256(31)) + newMemSize.Div(newMemSize, u256(32)) + newMemSize.Mul(newMemSize, u256(32)) + + if newMemSize.Cmp(u256(int64(mem.Len()))) > 0 { + memGasUsage := new(big.Int).Sub(newMemSize, u256(int64(mem.Len()))) + memGasUsage.Mul(GasMemory, memGasUsage) + memGasUsage.Div(memGasUsage, u256(32)) + + addStepGasUsage(memGasUsage) + } + } + + self.Printf("(pc) %-3d -o- %-14s", pc, op.String()) + self.Printf(" (g) %-3v (%v)", gas, closure.Gas) + + if !closure.UseGas(gas) { + self.Endl() + + err := fmt.Errorf("Insufficient gas for %v. req %v has %v", op, gas, closure.Gas) + + closure.UseGas(closure.Gas) + + return closure.Return(nil), err + } + + mem.Resize(newMemSize.Uint64()) + + switch op { + case LOG: + stack.Print() + mem.Print() + // 0x20 range + case ADD: + require(2) + x, y := stack.Popn() + self.Printf(" %v + %v", y, x) + + base.Add(y, x) + + U256(base) + + self.Printf(" = %v", base) + // Pop result back on the stack + stack.Push(base) + case SUB: + require(2) + x, y := stack.Popn() + self.Printf(" %v - %v", y, x) + + base.Sub(y, x) + + U256(base) + + self.Printf(" = %v", base) + // Pop result back on the stack + stack.Push(base) + case MUL: + require(2) + x, y := stack.Popn() + self.Printf(" %v * %v", y, x) + + base.Mul(y, x) + + U256(base) + + self.Printf(" = %v", base) + // Pop result back on the stack + stack.Push(base) + case DIV: + require(2) + x, y := stack.Pop(), stack.Pop() + self.Printf(" %v / %v", x, y) + + if y.Cmp(ethutil.Big0) != 0 { + base.Div(x, y) + } + + U256(base) + + self.Printf(" = %v", base) + // Pop result back on the stack + stack.Push(base) + case SDIV: + require(2) + x, y := S256(stack.Pop()), S256(stack.Pop()) + + self.Printf(" %v / %v", x, y) + + if y.Cmp(ethutil.Big0) == 0 { + base.Set(ethutil.Big0) + } else { + n := new(big.Int) + if new(big.Int).Mul(x, y).Cmp(ethutil.Big0) < 0 { + n.SetInt64(-1) + } else { + n.SetInt64(1) + } + + base.Div(x.Abs(x), y.Abs(y)).Mul(base, n) + + U256(base) + } + + self.Printf(" = %v", base) + stack.Push(base) + case MOD: + require(2) + x, y := stack.Pop(), stack.Pop() + + self.Printf(" %v %% %v", x, y) + + if y.Cmp(ethutil.Big0) == 0 { + base.Set(ethutil.Big0) + } else { + base.Mod(x, y) + } + + U256(base) + + self.Printf(" = %v", base) + stack.Push(base) + case SMOD: + require(2) + x, y := S256(stack.Pop()), S256(stack.Pop()) + + self.Printf(" %v %% %v", x, y) + + if y.Cmp(ethutil.Big0) == 0 { + base.Set(ethutil.Big0) + } else { + n := new(big.Int) + if x.Cmp(ethutil.Big0) < 0 { + n.SetInt64(-1) + } else { + n.SetInt64(1) + } + + base.Mod(x.Abs(x), y.Abs(y)).Mul(base, n) + + U256(base) + } + + self.Printf(" = %v", base) + stack.Push(base) + + case EXP: + require(2) + x, y := stack.Popn() + + self.Printf(" %v ** %v", y, x) + + base.Exp(y, x, Pow256) + + U256(base) + + self.Printf(" = %v", base) + + stack.Push(base) + case NEG: + require(1) + base.Sub(Pow256, stack.Pop()) + + base = U256(base) + + stack.Push(base) + case LT: + require(2) + x, y := stack.Popn() + self.Printf(" %v < %v", y, x) + // x < y + if y.Cmp(x) < 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case GT: + require(2) + x, y := stack.Popn() + self.Printf(" %v > %v", y, x) + + // x > y + if y.Cmp(x) > 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + + case SLT: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + self.Printf(" %v < %v", y, x) + // x < y + if y.Cmp(S256(x)) < 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case SGT: + require(2) + y, x := S256(stack.Pop()), S256(stack.Pop()) + self.Printf(" %v > %v", y, x) + + // x > y + if y.Cmp(x) > 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + + case EQ: + require(2) + x, y := stack.Popn() + self.Printf(" %v == %v", y, x) + + // x == y + if x.Cmp(y) == 0 { + stack.Push(ethutil.BigTrue) + } else { + stack.Push(ethutil.BigFalse) + } + case NOT: + require(1) + x := stack.Pop() + if x.Cmp(ethutil.BigFalse) > 0 { + stack.Push(ethutil.BigFalse) + } else { + stack.Push(ethutil.BigTrue) + } + + // 0x10 range + case AND: + require(2) + x, y := stack.Popn() + self.Printf(" %v & %v", y, x) + + stack.Push(base.And(y, x)) + case OR: + require(2) + x, y := stack.Popn() + self.Printf(" %v | %v", y, x) + + stack.Push(base.Or(y, x)) + case XOR: + require(2) + x, y := stack.Popn() + self.Printf(" %v ^ %v", y, x) + + stack.Push(base.Xor(y, x)) + case BYTE: + require(2) + val, th := stack.Popn() + + if th.Cmp(big.NewInt(32)) < 0 { + byt := big.NewInt(int64(ethutil.LeftPadBytes(val.Bytes(), 32)[th.Int64()])) + + base.Set(byt) + } else { + base.Set(ethutil.BigFalse) + } + + self.Printf(" => 0x%x", base.Bytes()) + + stack.Push(base) + case ADDMOD: + require(3) + + x := stack.Pop() + y := stack.Pop() + z := stack.Pop() + + base.Add(x, y) + base.Mod(base, z) + + U256(base) + + self.Printf(" = %v", base) + + stack.Push(base) + case MULMOD: + require(3) + + x := stack.Pop() + y := stack.Pop() + z := stack.Pop() + + base.Mul(x, y) + base.Mod(base, z) + + U256(base) + + self.Printf(" = %v", base) + + stack.Push(base) + + // 0x20 range + case SHA3: + require(2) + size, offset := stack.Popn() + data := ethcrypto.Sha3(mem.Get(offset.Int64(), size.Int64())) + + stack.Push(ethutil.BigD(data)) + + self.Printf(" => %x", data) + // 0x30 range + case ADDRESS: + stack.Push(ethutil.BigD(closure.Address())) + + self.Printf(" => %x", closure.Address()) + case BALANCE: + require(1) + + addr := stack.Pop().Bytes() + balance := state.GetBalance(addr) + + stack.Push(balance) + + self.Printf(" => %v (%x)", balance, addr) + case ORIGIN: + origin := self.env.Origin() + + stack.Push(ethutil.BigD(origin)) + + self.Printf(" => %x", origin) + case CALLER: + caller := closure.caller.Address() + stack.Push(ethutil.BigD(caller)) + + self.Printf(" => %x", caller) + case CALLVALUE: + value := closure.exe.value + + stack.Push(value) + + self.Printf(" => %v", value) + case CALLDATALOAD: + require(1) + var ( + offset = stack.Pop() + data = make([]byte, 32) + lenData = big.NewInt(int64(len(closure.Args))) + ) + + if lenData.Cmp(offset) >= 0 { + length := new(big.Int).Add(offset, ethutil.Big32) + length = ethutil.BigMin(length, lenData) + + copy(data, closure.Args[offset.Int64():length.Int64()]) + } + + self.Printf(" => 0x%x", data) + + stack.Push(ethutil.BigD(data)) + case CALLDATASIZE: + l := int64(len(closure.Args)) + stack.Push(big.NewInt(l)) + + self.Printf(" => %d", l) + case CALLDATACOPY: + var ( + size = int64(len(closure.Args)) + mOff = stack.Pop().Int64() + cOff = stack.Pop().Int64() + l = stack.Pop().Int64() + ) + + if cOff > size { + cOff = 0 + l = 0 + } else if cOff+l > size { + l = 0 + } + + code := closure.Args[cOff : cOff+l] + + mem.Set(mOff, l, code) + case CODESIZE, EXTCODESIZE: + var code []byte + if op == EXTCODESIZE { + addr := stack.Pop().Bytes() + + code = state.GetCode(addr) + } else { + code = closure.Code + } + + l := big.NewInt(int64(len(code))) + stack.Push(l) + + self.Printf(" => %d", l) + case CODECOPY, EXTCODECOPY: + var code []byte + if op == EXTCODECOPY { + addr := stack.Pop().Bytes() + + code = state.GetCode(addr) + } else { + code = closure.Code + } + + var ( + size = int64(len(code)) + mOff = stack.Pop().Int64() + cOff = stack.Pop().Int64() + l = stack.Pop().Int64() + ) + + if cOff > size { + cOff = 0 + l = 0 + } else if cOff+l > size { + l = 0 + } + + codeCopy := code[cOff : cOff+l] + + mem.Set(mOff, l, codeCopy) + case GASPRICE: + stack.Push(closure.Price) + + self.Printf(" => %v", closure.Price) + + // 0x40 range + case PREVHASH: + prevHash := self.env.PrevHash() + + stack.Push(ethutil.BigD(prevHash)) + + self.Printf(" => 0x%x", prevHash) + case COINBASE: + coinbase := self.env.Coinbase() + + stack.Push(ethutil.BigD(coinbase)) + + self.Printf(" => 0x%x", coinbase) + case TIMESTAMP: + time := self.env.Time() + + stack.Push(big.NewInt(time)) + + self.Printf(" => 0x%x", time) + case NUMBER: + number := self.env.BlockNumber() + + stack.Push(number) + + self.Printf(" => 0x%x", number.Bytes()) + case DIFFICULTY: + difficulty := self.env.Difficulty() + + stack.Push(difficulty) + + self.Printf(" => 0x%x", difficulty.Bytes()) + case GASLIMIT: + stack.Push(self.env.GasLimit()) + + // 0x50 range + case PUSH1, PUSH2, PUSH3, PUSH4, PUSH5, PUSH6, PUSH7, PUSH8, PUSH9, PUSH10, PUSH11, PUSH12, PUSH13, PUSH14, PUSH15, PUSH16, PUSH17, PUSH18, PUSH19, PUSH20, PUSH21, PUSH22, PUSH23, PUSH24, PUSH25, PUSH26, PUSH27, PUSH28, PUSH29, PUSH30, PUSH31, PUSH32: + a := big.NewInt(int64(op) - int64(PUSH1) + 1) + pc.Add(pc, ethutil.Big1) + data := closure.Gets(pc, a) + val := ethutil.BigD(data.Bytes()) + // Push value to stack + stack.Push(val) + pc.Add(pc, a.Sub(a, big.NewInt(1))) + + step += int(op) - int(PUSH1) + 1 + + self.Printf(" => 0x%x", data.Bytes()) + case POP: + require(1) + stack.Pop() + case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16: + n := int(op - DUP1 + 1) + v := stack.Dupn(n) + + self.Printf(" => [%d] 0x%x", n, stack.Peek().Bytes()) + + if OpCode(closure.Get(new(big.Int).Add(pc, ethutil.Big1)).Uint()) == POP && OpCode(closure.Get(new(big.Int).Add(pc, big.NewInt(2))).Uint()) == POP { + fmt.Println(toValue(v)) + } + case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16: + n := int(op - SWAP1 + 2) + x, y := stack.Swapn(n) + + self.Printf(" => [%d] %x [0] %x", n, x.Bytes(), y.Bytes()) + case MLOAD: + require(1) + offset := stack.Pop() + val := ethutil.BigD(mem.Get(offset.Int64(), 32)) + stack.Push(val) + + self.Printf(" => 0x%x", val.Bytes()) + case MSTORE: // Store the value at stack top-1 in to memory at location stack top + require(2) + // Pop value of the stack + val, mStart := stack.Popn() + mem.Set(mStart.Int64(), 32, ethutil.BigToBytes(val, 256)) + + self.Printf(" => 0x%x", val) + case MSTORE8: + require(2) + off := stack.Pop() + val := stack.Pop() + + mem.store[off.Int64()] = byte(val.Int64() & 0xff) + + self.Printf(" => [%v] 0x%x", off, val) + case SLOAD: + require(1) + loc := stack.Pop() + val := ethutil.BigD(state.GetState(closure.Address(), loc.Bytes())) + stack.Push(val) + + self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) + case SSTORE: + require(2) + val, loc := stack.Popn() + state.SetState(closure.Address(), loc.Bytes(), val) + + // Debug sessions are allowed to run without message + if closure.message != nil { + closure.message.AddStorageChange(loc.Bytes()) + } + + self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) + case JUMP: + require(1) + + jump(stack.Pop()) + + continue + case JUMPI: + require(2) + cond, pos := stack.Popn() + + if cond.Cmp(ethutil.BigTrue) >= 0 { + jump(pos) + + continue + } + + case JUMPDEST: + case PC: + stack.Push(pc) + case MSIZE: + stack.Push(big.NewInt(int64(mem.Len()))) + case GAS: + stack.Push(closure.Gas) + // 0x60 range + case CREATE: + require(3) + + var ( + err error + value = stack.Pop() + size, offset = stack.Popn() + input = mem.Get(offset.Int64(), size.Int64()) + gas = new(big.Int).Set(closure.Gas) + + // Snapshot the current stack so we are able to + // revert back to it later. + //snapshot = self.env.State().Copy() + ) + + // Generate a new address + n := state.GetNonce(closure.Address()) + addr := ethcrypto.CreateAddress(closure.Address(), n) + state.SetNonce(closure.Address(), n+1) + + self.Printf(" (*) %x", addr).Endl() + + closure.UseGas(closure.Gas) + + msg := NewExecution(self, addr, input, gas, closure.Price, value) + ret, err := msg.Create(closure) + if err != nil { + stack.Push(ethutil.BigFalse) + + // Revert the state as it was before. + //self.env.State().Set(snapshot) + + self.Printf("CREATE err %v", err) + } else { + msg.object.Code = ret + + stack.Push(ethutil.BigD(addr)) + } + + self.Endl() + + // Debug hook + if self.Dbg != nil { + self.Dbg.SetCode(closure.Code) + } + case CALL, CALLCODE: + require(7) + + self.Endl() + + gas := stack.Pop() + // Pop gas and value of the stack. + value, addr := stack.Popn() + // Pop input size and offset + inSize, inOffset := stack.Popn() + // Pop return size and offset + retSize, retOffset := stack.Popn() + + // Get the arguments from the memory + args := mem.Get(inOffset.Int64(), inSize.Int64()) + + var executeAddr []byte + if op == CALLCODE { + executeAddr = closure.Address() + } else { + executeAddr = addr.Bytes() + } + + msg := NewExecution(self, executeAddr, args, gas, closure.Price, value) + ret, err := msg.Exec(addr.Bytes(), closure) + if err != nil { + stack.Push(ethutil.BigFalse) + + vmlogger.Debugln(err) + } else { + stack.Push(ethutil.BigTrue) + + mem.Set(retOffset.Int64(), retSize.Int64(), ret) + } + self.Printf("resume %x", closure.Address()) + + // Debug hook + if self.Dbg != nil { + self.Dbg.SetCode(closure.Code) + } + + case RETURN: + require(2) + size, offset := stack.Popn() + ret := mem.Get(offset.Int64(), size.Int64()) + + self.Printf(" => (%d) 0x%x", len(ret), ret).Endl() + + return closure.Return(ret), nil + case SUICIDE: + require(1) + + receiver := state.GetOrNewStateObject(stack.Pop().Bytes()) + + receiver.AddAmount(state.GetBalance(closure.Address())) + state.Delete(closure.Address()) + + fallthrough + case STOP: // Stop the closure + self.Endl() + + return closure.Return(nil), nil + default: + vmlogger.Debugf("(pc) %-3v Invalid opcode %x\n", pc, op) + + //panic(fmt.Sprintf("Invalid opcode %x", op)) + closure.ReturnGas(big.NewInt(1), nil) + + return closure.Return(nil), fmt.Errorf("Invalid opcode %x", op) + } + + pc.Add(pc, ethutil.Big1) + + self.Endl() + + if self.Dbg != nil { + for _, instrNo := range self.Dbg.BreakPoints() { + if pc.Cmp(big.NewInt(instrNo)) == 0 { + self.Stepping = true + + if !self.Dbg.BreakHook(prevStep, op, mem, stack, state.GetStateObject(closure.Address())) { + return nil, nil + } + } else if self.Stepping { + if !self.Dbg.StepHook(prevStep, op, mem, stack, state.GetStateObject(closure.Address())) { + return nil, nil + } + } + } + } + + } +} + +func (self *DebugVm) Printf(format string, v ...interface{}) VirtualMachine { + if self.logTy == LogTyPretty { + self.logStr += fmt.Sprintf(format, v...) + } + + return self +} + +func (self *DebugVm) Endl() VirtualMachine { + if self.logTy == LogTyPretty { + vmlogger.Debugln(self.logStr) + self.logStr = "" + } + + return self +} + +func (self *DebugVm) Env() Environment { + return self.env +} + +func (self *DebugVm) Depth() int { + return self.depth +} diff --git a/vm/vm_test.go b/vm/vm_test.go new file mode 100644 index 000000000..047b76121 --- /dev/null +++ b/vm/vm_test.go @@ -0,0 +1,155 @@ +package vm + +import ( + "bytes" + "fmt" + "io/ioutil" + "log" + "math/big" + "os" + "testing" + + "github.com/ethereum/eth-go/ethcrypto" + "github.com/ethereum/eth-go/ethlog" + "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/ethtrie" + "github.com/ethereum/eth-go/ethutil" +) + +type TestEnv struct { +} + +func (self TestEnv) Origin() []byte { return nil } +func (self TestEnv) BlockNumber() *big.Int { return nil } +func (self TestEnv) BlockHash() []byte { return nil } +func (self TestEnv) PrevHash() []byte { return nil } +func (self TestEnv) Coinbase() []byte { return nil } +func (self TestEnv) Time() int64 { return 0 } +func (self TestEnv) Difficulty() *big.Int { return nil } +func (self TestEnv) Value() *big.Int { return nil } + +// This is likely to fail if anything ever gets looked up in the state trie :-) +func (self TestEnv) State() *ethstate.State { return ethstate.New(ethtrie.New(nil, "")) } + +const mutcode = ` +var x = 0; +for i := 0; i < 10; i++ { + x = i +} + +return x` + +func setup(level ethlog.LogLevel, typ Type) (*Closure, VirtualMachine) { + code, err := ethutil.Compile(mutcode, true) + if err != nil { + log.Fatal(err) + } + + // Pipe output to /dev/null + ethlog.AddLogSystem(ethlog.NewStdLogSystem(ioutil.Discard, log.LstdFlags, level)) + + ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "") + + stateObject := ethstate.NewStateObject([]byte{'j', 'e', 'f', 'f'}) + callerClosure := NewClosure(nil, stateObject, stateObject, code, big.NewInt(1000000), big.NewInt(0)) + + return callerClosure, New(TestEnv{}, typ) +} + +func TestDebugVm(t *testing.T) { + closure, vm := setup(ethlog.DebugLevel, DebugVmTy) + ret, _, e := closure.Call(vm, nil) + if e != nil { + fmt.Println("error", e) + } + + if ret[len(ret)-1] != 9 { + t.Errorf("Expected VM to return 9, got", ret, "instead.") + } +} + +func TestVm(t *testing.T) { + closure, vm := setup(ethlog.DebugLevel, StandardVmTy) + ret, _, e := closure.Call(vm, nil) + if e != nil { + fmt.Println("error", e) + } + + if ret[len(ret)-1] != 9 { + t.Errorf("Expected VM to return 9, got", ret, "instead.") + } +} + +func BenchmarkDebugVm(b *testing.B) { + closure, vm := setup(ethlog.InfoLevel, DebugVmTy) + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + closure.Call(vm, nil) + } +} + +func BenchmarkVm(b *testing.B) { + closure, vm := setup(ethlog.InfoLevel, StandardVmTy) + + b.ResetTimer() + + for i := 0; i < b.N; i++ { + closure.Call(vm, nil) + } +} + +func RunCode(mutCode string, typ Type) []byte { + code, err := ethutil.Compile(mutCode, true) + if err != nil { + log.Fatal(err) + } + + ethlog.AddLogSystem(ethlog.NewStdLogSystem(os.Stdout, log.LstdFlags, ethlog.InfoLevel)) + + ethutil.ReadConfig(".ethtest", "/tmp/ethtest", "") + + stateObject := ethstate.NewStateObject([]byte{'j', 'e', 'f', 'f'}) + closure := NewClosure(nil, stateObject, stateObject, code, big.NewInt(1000000), big.NewInt(0)) + + vm := New(TestEnv{}, typ) + ret, _, e := closure.Call(vm, nil) + if e != nil { + fmt.Println(e) + } + + return ret +} + +func TestBuildInSha256(t *testing.T) { + ret := RunCode(` + var in = 42 + var out = 0 + + call(0x2, 0, 10000, in, out) + + return out + `, DebugVmTy) + + exp := ethcrypto.Sha256(ethutil.LeftPadBytes([]byte{42}, 32)) + if bytes.Compare(ret, exp) != 0 { + t.Errorf("Expected %x, got %x", exp, ret) + } +} + +func TestBuildInRipemd(t *testing.T) { + ret := RunCode(` + var in = 42 + var out = 0 + + call(0x3, 0, 10000, in, out) + + return out + `, DebugVmTy) + + exp := ethutil.RightPadBytes(ethcrypto.Ripemd160(ethutil.LeftPadBytes([]byte{42}, 32)), 32) + if bytes.Compare(ret, exp) != 0 { + t.Errorf("Expected %x, got %x", exp, ret) + } +} -- cgit v1.2.3 From 097ba56df59293f9225a8ecdc9e1c43a5ad891bb Mon Sep 17 00:00:00 2001 From: obscuren Date: Mon, 20 Oct 2014 11:53:11 +0200 Subject: Renamed block_chain to chain_manager --- block_pool.go | 16 +-- ethchain/block_chain.go | 291 ----------------------------------------- ethchain/block_chain_test.go | 1 - ethchain/block_manager_test.go | 36 ----- ethchain/chain_manager.go | 291 +++++++++++++++++++++++++++++++++++++++++ ethchain/chain_manager_test.go | 1 + ethchain/filter.go | 8 +- ethchain/state_manager.go | 16 +-- ethchain/transaction_pool.go | 2 +- ethereum.go | 6 +- ethminer/miner.go | 12 +- ethpipe/js_pipe.go | 6 +- ethpipe/pipe.go | 4 +- peer.go | 29 ++-- tests/vm/gh_test.go | 9 +- vm/vm_debug.go | 2 +- 16 files changed, 347 insertions(+), 383 deletions(-) delete mode 100644 ethchain/block_chain.go delete mode 100644 ethchain/block_chain_test.go delete mode 100644 ethchain/block_manager_test.go create mode 100644 ethchain/chain_manager.go create mode 100644 ethchain/chain_manager_test.go (limited to 'vm') diff --git a/block_pool.go b/block_pool.go index 6ad2f5269..b2cade6ad 100644 --- a/block_pool.go +++ b/block_pool.go @@ -66,11 +66,11 @@ func (self *BlockPool) HasLatestHash() bool { self.mut.Lock() defer self.mut.Unlock() - return self.pool[string(self.eth.BlockChain().CurrentBlock.Hash())] != nil + return self.pool[string(self.eth.ChainManager().CurrentBlock.Hash())] != nil } func (self *BlockPool) HasCommonHash(hash []byte) bool { - return self.eth.BlockChain().GetBlock(hash) != nil + return self.eth.ChainManager().GetBlock(hash) != nil } func (self *BlockPool) Blocks() (blocks ethchain.Blocks) { @@ -137,7 +137,7 @@ func (self *BlockPool) addBlock(b *ethchain.Block, peer *Peer, newBlock bool) { hash := string(b.Hash()) - if self.pool[hash] == nil && !self.eth.BlockChain().HasBlock(b.Hash()) { + if self.pool[hash] == nil && !self.eth.ChainManager().HasBlock(b.Hash()) { poollogger.Infof("Got unrequested block (%x...)\n", hash[0:4]) self.hashes = append(self.hashes, b.Hash()) @@ -145,10 +145,10 @@ func (self *BlockPool) addBlock(b *ethchain.Block, peer *Peer, newBlock bool) { // The following is only performed on an unrequested new block if newBlock { - fmt.Println("1.", !self.eth.BlockChain().HasBlock(b.PrevHash), ethutil.Bytes2Hex(b.Hash()[0:4]), ethutil.Bytes2Hex(b.PrevHash[0:4])) + fmt.Println("1.", !self.eth.ChainManager().HasBlock(b.PrevHash), ethutil.Bytes2Hex(b.Hash()[0:4]), ethutil.Bytes2Hex(b.PrevHash[0:4])) fmt.Println("2.", self.pool[string(b.PrevHash)] == nil) fmt.Println("3.", !self.fetchingHashes) - if !self.eth.BlockChain().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes { + if !self.eth.ChainManager().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes { poollogger.Infof("Unknown chain, requesting (%x...)\n", b.PrevHash[0:4]) peer.QueueMessage(ethwire.NewMessage(ethwire.MsgGetBlockHashesTy, []interface{}{b.Hash(), uint32(256)})) } @@ -265,7 +265,7 @@ out: ethchain.BlockBy(ethchain.Number).Sort(blocks) if len(blocks) > 0 { - if !self.eth.BlockChain().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes { + if !self.eth.ChainManager().HasBlock(b.PrevHash) && self.pool[string(b.PrevHash)] == nil && !self.fetchingHashes { } } } @@ -287,14 +287,14 @@ out: // Find common block for i, block := range blocks { - if self.eth.BlockChain().HasBlock(block.PrevHash) { + if self.eth.ChainManager().HasBlock(block.PrevHash) { blocks = blocks[i:] break } } if len(blocks) > 0 { - if self.eth.BlockChain().HasBlock(blocks[0].PrevHash) { + if self.eth.ChainManager().HasBlock(blocks[0].PrevHash) { for i, block := range blocks[1:] { // NOTE: The Ith element in this loop refers to the previous block in // outer "blocks" diff --git a/ethchain/block_chain.go b/ethchain/block_chain.go deleted file mode 100644 index a5dcec438..000000000 --- a/ethchain/block_chain.go +++ /dev/null @@ -1,291 +0,0 @@ -package ethchain - -import ( - "bytes" - "fmt" - "math/big" - - "github.com/ethereum/eth-go/ethlog" - "github.com/ethereum/eth-go/ethutil" -) - -var chainlogger = ethlog.NewLogger("CHAIN") - -type BlockChain struct { - Ethereum EthManager - // The famous, the fabulous Mister GENESIIIIIIS (block) - genesisBlock *Block - // Last known total difficulty - TD *big.Int - - LastBlockNumber uint64 - - CurrentBlock *Block - LastBlockHash []byte -} - -func NewBlockChain(ethereum EthManager) *BlockChain { - bc := &BlockChain{} - bc.genesisBlock = NewBlockFromBytes(ethutil.Encode(Genesis)) - bc.Ethereum = ethereum - - bc.setLastBlock() - - return bc -} - -func (bc *BlockChain) Genesis() *Block { - return bc.genesisBlock -} - -func (bc *BlockChain) NewBlock(coinbase []byte) *Block { - var root interface{} - hash := ZeroHash256 - - if bc.CurrentBlock != nil { - root = bc.CurrentBlock.state.Trie.Root - hash = bc.LastBlockHash - } - - block := CreateBlock( - root, - hash, - coinbase, - ethutil.BigPow(2, 32), - nil, - "") - - block.MinGasPrice = big.NewInt(10000000000000) - - parent := bc.CurrentBlock - if parent != nil { - block.Difficulty = CalcDifficulty(block, parent) - block.Number = new(big.Int).Add(bc.CurrentBlock.Number, ethutil.Big1) - block.GasLimit = block.CalcGasLimit(bc.CurrentBlock) - - } - - return block -} - -func CalcDifficulty(block, parent *Block) *big.Int { - diff := new(big.Int) - - adjust := new(big.Int).Rsh(parent.Difficulty, 10) - if block.Time >= parent.Time+5 { - diff.Sub(parent.Difficulty, adjust) - } else { - diff.Add(parent.Difficulty, adjust) - } - - return diff -} - -func (bc *BlockChain) Reset() { - AddTestNetFunds(bc.genesisBlock) - - bc.genesisBlock.state.Trie.Sync() - // Prepare the genesis block - bc.Add(bc.genesisBlock) - fk := append([]byte("bloom"), bc.genesisBlock.Hash()...) - bc.Ethereum.Db().Put(fk, make([]byte, 255)) - bc.CurrentBlock = bc.genesisBlock - - bc.SetTotalDifficulty(ethutil.Big("0")) - - // Set the last know difficulty (might be 0x0 as initial value, Genesis) - bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD()) -} - -func (bc *BlockChain) HasBlock(hash []byte) bool { - data, _ := ethutil.Config.Db.Get(hash) - return len(data) != 0 -} - -// TODO: At one point we might want to save a block by prevHash in the db to optimise this... -func (bc *BlockChain) HasBlockWithPrevHash(hash []byte) bool { - block := bc.CurrentBlock - - for ; block != nil; block = bc.GetBlock(block.PrevHash) { - if bytes.Compare(hash, block.PrevHash) == 0 { - return true - } - } - return false -} - -func (bc *BlockChain) CalculateBlockTD(block *Block) *big.Int { - blockDiff := new(big.Int) - - for _, uncle := range block.Uncles { - blockDiff = blockDiff.Add(blockDiff, uncle.Difficulty) - } - blockDiff = blockDiff.Add(blockDiff, block.Difficulty) - - return blockDiff -} - -func (bc *BlockChain) GenesisBlock() *Block { - return bc.genesisBlock -} - -func (self *BlockChain) GetChainHashesFromHash(hash []byte, max uint64) (chain [][]byte) { - block := self.GetBlock(hash) - if block == nil { - return - } - - // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list) - for i := uint64(0); i < max; i++ { - chain = append(chain, block.Hash()) - - if block.Number.Cmp(ethutil.Big0) <= 0 { - break - } - - block = self.GetBlock(block.PrevHash) - } - - return -} - -func AddTestNetFunds(block *Block) { - for _, addr := range []string{ - "51ba59315b3a95761d0863b05ccc7a7f54703d99", - "e4157b34ea9615cfbde6b4fda419828124b70c78", - "b9c015918bdaba24b4ff057a92a3873d6eb201be", - "6c386a4b26f73c802f34673f7248bb118f97424a", - "cd2a3d9f938e13cd947ec05abc7fe734df8dd826", - "2ef47100e0787b915105fd5e3f4ff6752079d5cb", - "e6716f9544a56c530d868e4bfbacb172315bdead", - "1a26338f0d905e295fccb71fa9ea849ffa12aaf4", - } { - codedAddr := ethutil.Hex2Bytes(addr) - account := block.state.GetAccount(codedAddr) - account.Balance = ethutil.Big("1606938044258990275541962092341162602522202993782792835301376") //ethutil.BigPow(2, 200) - block.state.UpdateStateObject(account) - } -} - -func (bc *BlockChain) setLastBlock() { - data, _ := ethutil.Config.Db.Get([]byte("LastBlock")) - if len(data) != 0 { - // Prep genesis - AddTestNetFunds(bc.genesisBlock) - - block := NewBlockFromBytes(data) - bc.CurrentBlock = block - bc.LastBlockHash = block.Hash() - bc.LastBlockNumber = block.Number.Uint64() - - // Set the last know difficulty (might be 0x0 as initial value, Genesis) - bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD()) - } else { - bc.Reset() - } - - chainlogger.Infof("Last block (#%d) %x\n", bc.LastBlockNumber, bc.CurrentBlock.Hash()) -} - -func (bc *BlockChain) SetTotalDifficulty(td *big.Int) { - ethutil.Config.Db.Put([]byte("LTD"), td.Bytes()) - bc.TD = td -} - -// Add a block to the chain and record addition information -func (bc *BlockChain) Add(block *Block) { - bc.writeBlockInfo(block) - // Prepare the genesis block - - bc.CurrentBlock = block - bc.LastBlockHash = block.Hash() - - encodedBlock := block.RlpEncode() - ethutil.Config.Db.Put(block.Hash(), encodedBlock) - ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock) -} - -func (self *BlockChain) CalcTotalDiff(block *Block) (*big.Int, error) { - parent := self.GetBlock(block.PrevHash) - if parent == nil { - return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash) - } - - parentTd := parent.BlockInfo().TD - - uncleDiff := new(big.Int) - for _, uncle := range block.Uncles { - uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty) - } - - td := new(big.Int) - td = td.Add(parentTd, uncleDiff) - td = td.Add(td, block.Difficulty) - - return td, nil -} - -func (bc *BlockChain) GetBlock(hash []byte) *Block { - data, _ := ethutil.Config.Db.Get(hash) - if len(data) == 0 { - return nil - } - - return NewBlockFromBytes(data) -} - -func (self *BlockChain) GetBlockByNumber(num uint64) *Block { - block := self.CurrentBlock - for ; block != nil; block = self.GetBlock(block.PrevHash) { - if block.Number.Uint64() == num { - break - } - } - - if block != nil && block.Number.Uint64() == 0 && num != 0 { - return nil - } - - return block -} - -func (self *BlockChain) GetBlockBack(num uint64) *Block { - block := self.CurrentBlock - - for ; num != 0 && block != nil; num-- { - block = self.GetBlock(block.PrevHash) - } - - return block -} - -func (bc *BlockChain) BlockInfoByHash(hash []byte) BlockInfo { - bi := BlockInfo{} - data, _ := ethutil.Config.Db.Get(append(hash, []byte("Info")...)) - bi.RlpDecode(data) - - return bi -} - -func (bc *BlockChain) BlockInfo(block *Block) BlockInfo { - bi := BlockInfo{} - data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...)) - bi.RlpDecode(data) - - return bi -} - -// Unexported method for writing extra non-essential block info to the db -func (bc *BlockChain) writeBlockInfo(block *Block) { - bc.LastBlockNumber++ - bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD} - - // For now we use the block hash with the words "info" appended as key - ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode()) -} - -func (bc *BlockChain) Stop() { - if bc.CurrentBlock != nil { - chainlogger.Infoln("Stopped") - } -} diff --git a/ethchain/block_chain_test.go b/ethchain/block_chain_test.go deleted file mode 100644 index 3603fd8a7..000000000 --- a/ethchain/block_chain_test.go +++ /dev/null @@ -1 +0,0 @@ -package ethchain diff --git a/ethchain/block_manager_test.go b/ethchain/block_manager_test.go deleted file mode 100644 index 3a1e5f510..000000000 --- a/ethchain/block_manager_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package ethchain - -/* -import ( - _ "fmt" - "github.com/ethereum/eth-go/ethdb" - "github.com/ethereum/eth-go/ethutil" - "math/big" - "testing" -) - -func TestVm(t *testing.T) { - InitFees() - ethutil.ReadConfig("") - - db, _ := ethdb.NewMemDatabase() - ethutil.Config.Db = db - bm := NewStateManager(nil) - - block := bm.bc.genesisBlock - bm.Prepare(block.State(), block.State()) - script := Compile([]string{ - "PUSH", - "1", - "PUSH", - "2", - }) - tx := NewTransaction(ContractAddr, big.NewInt(200000000), script) - addr := tx.Hash()[12:] - bm.ApplyTransactions(block, []*Transaction{tx}) - - tx2 := NewTransaction(addr, big.NewInt(1e17), nil) - tx2.Sign([]byte("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")) - bm.ApplyTransactions(block, []*Transaction{tx2}) -} -*/ diff --git a/ethchain/chain_manager.go b/ethchain/chain_manager.go new file mode 100644 index 000000000..227b02c0a --- /dev/null +++ b/ethchain/chain_manager.go @@ -0,0 +1,291 @@ +package ethchain + +import ( + "bytes" + "fmt" + "math/big" + + "github.com/ethereum/eth-go/ethlog" + "github.com/ethereum/eth-go/ethutil" +) + +var chainlogger = ethlog.NewLogger("CHAIN") + +type ChainManager struct { + Ethereum EthManager + // The famous, the fabulous Mister GENESIIIIIIS (block) + genesisBlock *Block + // Last known total difficulty + TD *big.Int + + LastBlockNumber uint64 + + CurrentBlock *Block + LastBlockHash []byte +} + +func NewChainManager(ethereum EthManager) *ChainManager { + bc := &ChainManager{} + bc.genesisBlock = NewBlockFromBytes(ethutil.Encode(Genesis)) + bc.Ethereum = ethereum + + bc.setLastBlock() + + return bc +} + +func (bc *ChainManager) Genesis() *Block { + return bc.genesisBlock +} + +func (bc *ChainManager) NewBlock(coinbase []byte) *Block { + var root interface{} + hash := ZeroHash256 + + if bc.CurrentBlock != nil { + root = bc.CurrentBlock.state.Trie.Root + hash = bc.LastBlockHash + } + + block := CreateBlock( + root, + hash, + coinbase, + ethutil.BigPow(2, 32), + nil, + "") + + block.MinGasPrice = big.NewInt(10000000000000) + + parent := bc.CurrentBlock + if parent != nil { + block.Difficulty = CalcDifficulty(block, parent) + block.Number = new(big.Int).Add(bc.CurrentBlock.Number, ethutil.Big1) + block.GasLimit = block.CalcGasLimit(bc.CurrentBlock) + + } + + return block +} + +func CalcDifficulty(block, parent *Block) *big.Int { + diff := new(big.Int) + + adjust := new(big.Int).Rsh(parent.Difficulty, 10) + if block.Time >= parent.Time+5 { + diff.Sub(parent.Difficulty, adjust) + } else { + diff.Add(parent.Difficulty, adjust) + } + + return diff +} + +func (bc *ChainManager) Reset() { + AddTestNetFunds(bc.genesisBlock) + + bc.genesisBlock.state.Trie.Sync() + // Prepare the genesis block + bc.Add(bc.genesisBlock) + fk := append([]byte("bloom"), bc.genesisBlock.Hash()...) + bc.Ethereum.Db().Put(fk, make([]byte, 255)) + bc.CurrentBlock = bc.genesisBlock + + bc.SetTotalDifficulty(ethutil.Big("0")) + + // Set the last know difficulty (might be 0x0 as initial value, Genesis) + bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD()) +} + +func (bc *ChainManager) HasBlock(hash []byte) bool { + data, _ := ethutil.Config.Db.Get(hash) + return len(data) != 0 +} + +// TODO: At one point we might want to save a block by prevHash in the db to optimise this... +func (bc *ChainManager) HasBlockWithPrevHash(hash []byte) bool { + block := bc.CurrentBlock + + for ; block != nil; block = bc.GetBlock(block.PrevHash) { + if bytes.Compare(hash, block.PrevHash) == 0 { + return true + } + } + return false +} + +func (bc *ChainManager) CalculateBlockTD(block *Block) *big.Int { + blockDiff := new(big.Int) + + for _, uncle := range block.Uncles { + blockDiff = blockDiff.Add(blockDiff, uncle.Difficulty) + } + blockDiff = blockDiff.Add(blockDiff, block.Difficulty) + + return blockDiff +} + +func (bc *ChainManager) GenesisBlock() *Block { + return bc.genesisBlock +} + +func (self *ChainManager) GetChainHashesFromHash(hash []byte, max uint64) (chain [][]byte) { + block := self.GetBlock(hash) + if block == nil { + return + } + + // XXX Could be optimised by using a different database which only holds hashes (i.e., linked list) + for i := uint64(0); i < max; i++ { + chain = append(chain, block.Hash()) + + if block.Number.Cmp(ethutil.Big0) <= 0 { + break + } + + block = self.GetBlock(block.PrevHash) + } + + return +} + +func AddTestNetFunds(block *Block) { + for _, addr := range []string{ + "51ba59315b3a95761d0863b05ccc7a7f54703d99", + "e4157b34ea9615cfbde6b4fda419828124b70c78", + "b9c015918bdaba24b4ff057a92a3873d6eb201be", + "6c386a4b26f73c802f34673f7248bb118f97424a", + "cd2a3d9f938e13cd947ec05abc7fe734df8dd826", + "2ef47100e0787b915105fd5e3f4ff6752079d5cb", + "e6716f9544a56c530d868e4bfbacb172315bdead", + "1a26338f0d905e295fccb71fa9ea849ffa12aaf4", + } { + codedAddr := ethutil.Hex2Bytes(addr) + account := block.state.GetAccount(codedAddr) + account.Balance = ethutil.Big("1606938044258990275541962092341162602522202993782792835301376") //ethutil.BigPow(2, 200) + block.state.UpdateStateObject(account) + } +} + +func (bc *ChainManager) setLastBlock() { + data, _ := ethutil.Config.Db.Get([]byte("LastBlock")) + if len(data) != 0 { + // Prep genesis + AddTestNetFunds(bc.genesisBlock) + + block := NewBlockFromBytes(data) + bc.CurrentBlock = block + bc.LastBlockHash = block.Hash() + bc.LastBlockNumber = block.Number.Uint64() + + // Set the last know difficulty (might be 0x0 as initial value, Genesis) + bc.TD = ethutil.BigD(ethutil.Config.Db.LastKnownTD()) + } else { + bc.Reset() + } + + chainlogger.Infof("Last block (#%d) %x\n", bc.LastBlockNumber, bc.CurrentBlock.Hash()) +} + +func (bc *ChainManager) SetTotalDifficulty(td *big.Int) { + ethutil.Config.Db.Put([]byte("LTD"), td.Bytes()) + bc.TD = td +} + +// Add a block to the chain and record addition information +func (bc *ChainManager) Add(block *Block) { + bc.writeBlockInfo(block) + // Prepare the genesis block + + bc.CurrentBlock = block + bc.LastBlockHash = block.Hash() + + encodedBlock := block.RlpEncode() + ethutil.Config.Db.Put(block.Hash(), encodedBlock) + ethutil.Config.Db.Put([]byte("LastBlock"), encodedBlock) +} + +func (self *ChainManager) CalcTotalDiff(block *Block) (*big.Int, error) { + parent := self.GetBlock(block.PrevHash) + if parent == nil { + return nil, fmt.Errorf("Unable to calculate total diff without known parent %x", block.PrevHash) + } + + parentTd := parent.BlockInfo().TD + + uncleDiff := new(big.Int) + for _, uncle := range block.Uncles { + uncleDiff = uncleDiff.Add(uncleDiff, uncle.Difficulty) + } + + td := new(big.Int) + td = td.Add(parentTd, uncleDiff) + td = td.Add(td, block.Difficulty) + + return td, nil +} + +func (bc *ChainManager) GetBlock(hash []byte) *Block { + data, _ := ethutil.Config.Db.Get(hash) + if len(data) == 0 { + return nil + } + + return NewBlockFromBytes(data) +} + +func (self *ChainManager) GetBlockByNumber(num uint64) *Block { + block := self.CurrentBlock + for ; block != nil; block = self.GetBlock(block.PrevHash) { + if block.Number.Uint64() == num { + break + } + } + + if block != nil && block.Number.Uint64() == 0 && num != 0 { + return nil + } + + return block +} + +func (self *ChainManager) GetBlockBack(num uint64) *Block { + block := self.CurrentBlock + + for ; num != 0 && block != nil; num-- { + block = self.GetBlock(block.PrevHash) + } + + return block +} + +func (bc *ChainManager) BlockInfoByHash(hash []byte) BlockInfo { + bi := BlockInfo{} + data, _ := ethutil.Config.Db.Get(append(hash, []byte("Info")...)) + bi.RlpDecode(data) + + return bi +} + +func (bc *ChainManager) BlockInfo(block *Block) BlockInfo { + bi := BlockInfo{} + data, _ := ethutil.Config.Db.Get(append(block.Hash(), []byte("Info")...)) + bi.RlpDecode(data) + + return bi +} + +// Unexported method for writing extra non-essential block info to the db +func (bc *ChainManager) writeBlockInfo(block *Block) { + bc.LastBlockNumber++ + bi := BlockInfo{Number: bc.LastBlockNumber, Hash: block.Hash(), Parent: block.PrevHash, TD: bc.TD} + + // For now we use the block hash with the words "info" appended as key + ethutil.Config.Db.Put(append(block.Hash(), []byte("Info")...), bi.RlpEncode()) +} + +func (bc *ChainManager) Stop() { + if bc.CurrentBlock != nil { + chainlogger.Infoln("Stopped") + } +} diff --git a/ethchain/chain_manager_test.go b/ethchain/chain_manager_test.go new file mode 100644 index 000000000..3603fd8a7 --- /dev/null +++ b/ethchain/chain_manager_test.go @@ -0,0 +1 @@ +package ethchain diff --git a/ethchain/filter.go b/ethchain/filter.go index 90f2512ab..4e8df7d5f 100644 --- a/ethchain/filter.go +++ b/ethchain/filter.go @@ -76,16 +76,16 @@ func (self *Filter) SetSkip(skip int) { func (self *Filter) Find() []*ethstate.Message { var earliestBlockNo uint64 = uint64(self.earliest) if self.earliest == -1 { - earliestBlockNo = self.eth.BlockChain().CurrentBlock.Number.Uint64() + earliestBlockNo = self.eth.ChainManager().CurrentBlock.Number.Uint64() } var latestBlockNo uint64 = uint64(self.latest) if self.latest == -1 { - latestBlockNo = self.eth.BlockChain().CurrentBlock.Number.Uint64() + latestBlockNo = self.eth.ChainManager().CurrentBlock.Number.Uint64() } var ( messages []*ethstate.Message - block = self.eth.BlockChain().GetBlockByNumber(latestBlockNo) + block = self.eth.ChainManager().GetBlockByNumber(latestBlockNo) quit bool ) for i := 0; !quit && block != nil; i++ { @@ -111,7 +111,7 @@ func (self *Filter) Find() []*ethstate.Message { messages = append(messages, self.FilterMessages(msgs)...) } - block = self.eth.BlockChain().GetBlock(block.PrevHash) + block = self.eth.ChainManager().GetBlock(block.PrevHash) } skip := int(math.Min(float64(len(messages)), float64(self.skip))) diff --git a/ethchain/state_manager.go b/ethchain/state_manager.go index b71cbe8a1..ed513c9dc 100644 --- a/ethchain/state_manager.go +++ b/ethchain/state_manager.go @@ -33,7 +33,7 @@ type Peer interface { type EthManager interface { StateManager() *StateManager - BlockChain() *BlockChain + ChainManager() *ChainManager TxPool() *TxPool Broadcast(msgType ethwire.MsgType, data []interface{}) PeerCount() int @@ -50,7 +50,7 @@ type StateManager struct { // Mutex for locking the block processor. Blocks can only be handled one at a time mutex sync.Mutex // Canonical block chain - bc *BlockChain + bc *ChainManager // non-persistent key/value memory storage mem map[string]*big.Int // Proof of work used for validating @@ -79,10 +79,10 @@ func NewStateManager(ethereum EthManager) *StateManager { mem: make(map[string]*big.Int), Pow: &EasyPow{}, eth: ethereum, - bc: ethereum.BlockChain(), + bc: ethereum.ChainManager(), } - sm.transState = ethereum.BlockChain().CurrentBlock.State().Copy() - sm.miningState = ethereum.BlockChain().CurrentBlock.State().Copy() + sm.transState = ethereum.ChainManager().CurrentBlock.State().Copy() + sm.miningState = ethereum.ChainManager().CurrentBlock.State().Copy() return sm } @@ -113,7 +113,7 @@ func (self *StateManager) updateThread() { } func (sm *StateManager) CurrentState() *ethstate.State { - return sm.eth.BlockChain().CurrentBlock.State() + return sm.eth.ChainManager().CurrentBlock.State() } func (sm *StateManager) TransState() *ethstate.State { @@ -125,12 +125,12 @@ func (sm *StateManager) MiningState() *ethstate.State { } func (sm *StateManager) NewMiningState() *ethstate.State { - sm.miningState = sm.eth.BlockChain().CurrentBlock.State().Copy() + sm.miningState = sm.eth.ChainManager().CurrentBlock.State().Copy() return sm.miningState } -func (sm *StateManager) BlockChain() *BlockChain { +func (sm *StateManager) ChainManager() *ChainManager { return sm.bc } diff --git a/ethchain/transaction_pool.go b/ethchain/transaction_pool.go index 0676af3a3..ff3184582 100644 --- a/ethchain/transaction_pool.go +++ b/ethchain/transaction_pool.go @@ -96,7 +96,7 @@ func (pool *TxPool) addTransaction(tx *Transaction) { func (pool *TxPool) ValidateTransaction(tx *Transaction) error { // Get the last block so we can retrieve the sender and receiver from // the merkle trie - block := pool.Ethereum.BlockChain().CurrentBlock + block := pool.Ethereum.ChainManager().CurrentBlock // Something has gone horribly wrong if this happens if block == nil { return fmt.Errorf("[TXPL] No last block on the block chain") diff --git a/ethereum.go b/ethereum.go index e5f73d507..bb8d6db73 100644 --- a/ethereum.go +++ b/ethereum.go @@ -55,7 +55,7 @@ type Ethereum struct { // for later including in the blocks txPool *ethchain.TxPool // The canonical chain - blockChain *ethchain.BlockChain + blockChain *ethchain.ChainManager // The block pool blockPool *BlockPool // Eventer @@ -129,7 +129,7 @@ func New(db ethutil.Database, clientIdentity ethwire.ClientIdentity, keyManager ethereum.blockPool = NewBlockPool(ethereum) ethereum.txPool = ethchain.NewTxPool(ethereum) - ethereum.blockChain = ethchain.NewBlockChain(ethereum) + ethereum.blockChain = ethchain.NewChainManager(ethereum) ethereum.stateManager = ethchain.NewStateManager(ethereum) // Start the tx pool @@ -146,7 +146,7 @@ func (s *Ethereum) ClientIdentity() ethwire.ClientIdentity { return s.clientIdentity } -func (s *Ethereum) BlockChain() *ethchain.BlockChain { +func (s *Ethereum) ChainManager() *ethchain.ChainManager { return s.blockChain } diff --git a/ethminer/miner.go b/ethminer/miner.go index ffc49f096..69f6e4bf6 100644 --- a/ethminer/miner.go +++ b/ethminer/miner.go @@ -61,7 +61,7 @@ func (miner *Miner) Start() { // Insert initial TXs in our little miner 'pool' miner.txs = miner.ethereum.TxPool().Flush() - miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase) + miner.block = miner.ethereum.ChainManager().NewBlock(miner.coinbase) mux := miner.ethereum.EventMux() miner.events = mux.Subscribe(ethchain.NewBlockEvent{}, ethchain.TxEvent{}) @@ -95,7 +95,7 @@ func (miner *Miner) listener() { case ethchain.NewBlockEvent: block := event.Block //logger.Infoln("Got new block via Reactor") - if bytes.Compare(miner.ethereum.BlockChain().CurrentBlock.Hash(), block.Hash()) == 0 { + if bytes.Compare(miner.ethereum.ChainManager().CurrentBlock.Hash(), block.Hash()) == 0 { // TODO: Perhaps continue mining to get some uncle rewards //logger.Infoln("New top block found resetting state") @@ -115,10 +115,10 @@ func (miner *Miner) listener() { miner.txs = newtxs // Setup a fresh state to mine on - //miner.block = miner.ethereum.BlockChain().NewBlock(miner.coinbase, miner.txs) + //miner.block = miner.ethereum.ChainManager().NewBlock(miner.coinbase, miner.txs) } else { - if bytes.Compare(block.PrevHash, miner.ethereum.BlockChain().CurrentBlock.PrevHash) == 0 { + if bytes.Compare(block.PrevHash, miner.ethereum.ChainManager().CurrentBlock.PrevHash) == 0 { logger.Infoln("Adding uncle block") miner.uncles = append(miner.uncles, block) } @@ -163,7 +163,7 @@ func (miner *Miner) stopMining() { func (self *Miner) mineNewBlock() { stateManager := self.ethereum.StateManager() - self.block = self.ethereum.BlockChain().NewBlock(self.coinbase) + self.block = self.ethereum.ChainManager().NewBlock(self.coinbase) // Apply uncles if len(self.uncles) > 0 { @@ -175,7 +175,7 @@ func (self *Miner) mineNewBlock() { // Accumulate all valid transactions and apply them to the new state // Error may be ignored. It's not important during mining - parent := self.ethereum.BlockChain().GetBlock(self.block.PrevHash) + parent := self.ethereum.ChainManager().GetBlock(self.block.PrevHash) coinbase := self.block.State().GetOrNewStateObject(self.block.Coinbase) coinbase.SetGasPool(self.block.CalcGasLimit(parent)) receipts, txs, unhandledTxs, err := stateManager.ProcessTransactions(coinbase, self.block.State(), self.block, self.block, self.txs) diff --git a/ethpipe/js_pipe.go b/ethpipe/js_pipe.go index 24a553dad..873373b75 100644 --- a/ethpipe/js_pipe.go +++ b/ethpipe/js_pipe.go @@ -21,17 +21,17 @@ func NewJSPipe(eth ethchain.EthManager) *JSPipe { func (self *JSPipe) BlockByHash(strHash string) *JSBlock { hash := ethutil.Hex2Bytes(strHash) - block := self.obj.BlockChain().GetBlock(hash) + block := self.obj.ChainManager().GetBlock(hash) return NewJSBlock(block) } func (self *JSPipe) BlockByNumber(num int32) *JSBlock { if num == -1 { - return NewJSBlock(self.obj.BlockChain().CurrentBlock) + return NewJSBlock(self.obj.ChainManager().CurrentBlock) } - return NewJSBlock(self.obj.BlockChain().GetBlockByNumber(uint64(num))) + return NewJSBlock(self.obj.ChainManager().GetBlockByNumber(uint64(num))) } func (self *JSPipe) Block(v interface{}) *JSBlock { diff --git a/ethpipe/pipe.go b/ethpipe/pipe.go index 5e5ff7000..50507143c 100644 --- a/ethpipe/pipe.go +++ b/ethpipe/pipe.go @@ -21,7 +21,7 @@ type VmVars struct { type Pipe struct { obj ethchain.EthManager stateManager *ethchain.StateManager - blockChain *ethchain.BlockChain + blockChain *ethchain.ChainManager world *World Vm VmVars @@ -31,7 +31,7 @@ func New(obj ethchain.EthManager) *Pipe { pipe := &Pipe{ obj: obj, stateManager: obj.StateManager(), - blockChain: obj.BlockChain(), + blockChain: obj.ChainManager(), } pipe.world = NewWorld(pipe) diff --git a/peer.go b/peer.go index 52eb20cfc..0eb2eb299 100644 --- a/peer.go +++ b/peer.go @@ -476,7 +476,7 @@ func (p *Peer) HandleInbound() { hash := msg.Data.Get(0).Bytes() amount := msg.Data.Get(1).Uint() - hashes := p.ethereum.BlockChain().GetChainHashesFromHash(hash, amount) + hashes := p.ethereum.ChainManager().GetChainHashesFromHash(hash, amount) p.QueueMessage(ethwire.NewMessage(ethwire.MsgBlockHashesTy, ethutil.ByteSliceToInterface(hashes))) @@ -487,7 +487,7 @@ func (p *Peer) HandleInbound() { for i := 0; i < max; i++ { hash := msg.Data.Get(i).Bytes() - block := p.ethereum.BlockChain().GetBlock(hash) + block := p.ethereum.ChainManager().GetBlock(hash) if block != nil { blocks = append(blocks, block.Value().Raw()) } @@ -674,9 +674,9 @@ func (self *Peer) pushStatus() { msg := ethwire.NewMessage(ethwire.MsgStatusTy, []interface{}{ //uint32(ProtocolVersion), uint32(NetVersion), - self.ethereum.BlockChain().TD, - self.ethereum.BlockChain().CurrentBlock.Hash(), - self.ethereum.BlockChain().Genesis().Hash(), + self.ethereum.ChainManager().TD, + self.ethereum.ChainManager().CurrentBlock.Hash(), + self.ethereum.ChainManager().Genesis().Hash(), }) self.QueueMessage(msg) @@ -693,7 +693,7 @@ func (self *Peer) handleStatus(msg *ethwire.Msg) { genesis = c.Get(3).Bytes() ) - if bytes.Compare(self.ethereum.BlockChain().Genesis().Hash(), genesis) != 0 { + if bytes.Compare(self.ethereum.ChainManager().Genesis().Hash(), genesis) != 0 { ethlogger.Warnf("Invalid genisis hash %x. Disabling [eth]\n", genesis) return } @@ -728,7 +728,7 @@ func (self *Peer) handleStatus(msg *ethwire.Msg) { func (p *Peer) pushHandshake() error { pubkey := p.ethereum.KeyManager().PublicKey() msg := ethwire.NewMessage(ethwire.MsgHandshakeTy, []interface{}{ - P2PVersion, []byte(p.version), []interface{}{"eth", ProtocolVersion}, p.port, pubkey[1:], + P2PVersion, []byte(p.version), []interface{}{[]interface{}{"eth", ProtocolVersion}}, p.port, pubkey[1:], }) p.QueueMessage(msg) @@ -749,6 +749,7 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) { // Check correctness of p2p protocol version if p2pVersion != P2PVersion { + fmt.Println(p) peerlogger.Debugf("Invalid P2P version. Require protocol %d, received %d\n", P2PVersion, p2pVersion) p.Stop() return @@ -807,16 +808,16 @@ func (p *Peer) handleHandshake(msg *ethwire.Msg) { p.ethereum.eventMux.Post(PeerListEvent{p.ethereum.Peers()}) p.protocolCaps = caps - capsIt := caps.NewIterator() + + it := caps.NewIterator() var capsStrs []string - for capsIt.Next() { - cap := capsIt.Value().Str() + for it.Next() { + cap := it.Value().Get(0).Str() + ver := it.Value().Get(1).Uint() switch cap { case "eth": - capsIt.Next() - version := capsIt.Value().Uint() - if version != ProtocolVersion { - ethlogger.Warnf("Invalid protocol version %d. Disabling [eth]\n", version) + if ver != ProtocolVersion { + ethlogger.Warnf("Invalid protocol version %d. Disabling [eth]\n", ver) continue } p.pushStatus() diff --git a/tests/vm/gh_test.go b/tests/vm/gh_test.go index 466fae9c7..f27cc7af3 100644 --- a/tests/vm/gh_test.go +++ b/tests/vm/gh_test.go @@ -44,6 +44,9 @@ func RunVmTest(p string, t *testing.T) { helper.CreateFileTests(t, p, &tests) for name, test := range tests { + if name != "CallRecursiveBomb" { + continue + } state := ethstate.New(helper.NewTrie()) for addr, account := range test.Pre { obj := StateObjectFromAccount(addr, account) @@ -56,11 +59,6 @@ func RunVmTest(p string, t *testing.T) { if err != nil { helper.Log.Infoln(err) } - /* - if err != nil { - t.Errorf("%s's execution failed. %v\n", name, err) - } - */ rexp := helper.FromHex(test.Out) if bytes.Compare(rexp, ret) != 0 { @@ -94,6 +92,7 @@ func TestVMArithmetic(t *testing.T) { } func TestVMSystemOperation(t *testing.T) { + helper.Logger.SetLogLevel(5) const fn = "../files/vmtests/vmSystemOperationsTest.json" RunVmTest(fn, t) } diff --git a/vm/vm_debug.go b/vm/vm_debug.go index 785e699c7..8773df087 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -97,7 +97,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { return closure.Return(nil), nil } - vmlogger.Debugf("(%s) %x gas: %v (d) %x\n", self.Fn, closure.Address(), closure.Gas, closure.Args) + vmlogger.Debugf("(%d) %x gas: %v (d) %x\n", self.depth, closure.Address(), closure.Gas, closure.Args) for { prevStep = step -- cgit v1.2.3 From b5beb1aac11af92bfe0f3ed7560b9eb08495ed09 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 22 Oct 2014 15:22:21 +0200 Subject: added a transfer method to vm env --- ethstate/dump.go | 2 +- ethstate/state.go | 2 +- ethstate/state_object.go | 40 ++++++++++++++++++++++------------------ peer.go | 2 +- tests/helper/vm.go | 5 ++++- tests/vm/gh_test.go | 6 +----- vm/environment.go | 20 ++++++++++++++++++++ vm/execution.go | 16 ++++++++-------- vm/vm.go | 2 +- 9 files changed, 59 insertions(+), 36 deletions(-) (limited to 'vm') diff --git a/ethstate/dump.go b/ethstate/dump.go index cdd4228b8..e7cbde48b 100644 --- a/ethstate/dump.go +++ b/ethstate/dump.go @@ -28,7 +28,7 @@ func (self *State) Dump() []byte { self.Trie.NewIterator().Each(func(key string, value *ethutil.Value) { stateObject := NewStateObjectFromBytes([]byte(key), value.Bytes()) - account := Account{Balance: stateObject.Balance.String(), Nonce: stateObject.Nonce, CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)} + account := Account{Balance: stateObject.balance.String(), Nonce: stateObject.Nonce, CodeHash: ethutil.Bytes2Hex(stateObject.codeHash)} account.Storage = make(map[string]string) stateObject.EachStorage(func(key string, value *ethutil.Value) { diff --git a/ethstate/state.go b/ethstate/state.go index 2efe2a311..59d2265a9 100644 --- a/ethstate/state.go +++ b/ethstate/state.go @@ -33,7 +33,7 @@ func New(trie *ethtrie.Trie) *State { func (self *State) GetBalance(addr []byte) *big.Int { stateObject := self.GetStateObject(addr) if stateObject != nil { - return stateObject.Balance + return stateObject.balance } return ethutil.Big0 diff --git a/ethstate/state_object.go b/ethstate/state_object.go index a5b7c65e9..1ba005439 100644 --- a/ethstate/state_object.go +++ b/ethstate/state_object.go @@ -31,7 +31,7 @@ type StateObject struct { // Address of the object address []byte // Shared attributes - Balance *big.Int + balance *big.Int codeHash []byte Nonce uint64 // Contract related attributes @@ -61,7 +61,7 @@ func NewStateObject(addr []byte) *StateObject { // This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter. address := ethutil.Address(addr) - object := &StateObject{address: address, Balance: new(big.Int), gasPool: new(big.Int)} + object := &StateObject{address: address, balance: new(big.Int), gasPool: new(big.Int)} object.State = New(ethtrie.New(ethutil.Config.Db, "")) object.storage = make(Storage) object.gasPool = new(big.Int) @@ -71,7 +71,7 @@ func NewStateObject(addr []byte) *StateObject { func NewContract(address []byte, balance *big.Int, root []byte) *StateObject { contract := NewStateObject(address) - contract.Balance = balance + contract.balance = balance contract.State = New(ethtrie.New(ethutil.Config.Db, string(root))) return contract @@ -86,7 +86,7 @@ func NewStateObjectFromBytes(address, data []byte) *StateObject { func (self *StateObject) MarkForDeletion() { self.remove = true - statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.Balance) + statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.balance) } func (c *StateObject) GetAddr(addr []byte) *ethutil.Value { @@ -174,22 +174,26 @@ func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value { return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]}) } -func (c *StateObject) AddAmount(amount *big.Int) { - c.SetBalance(new(big.Int).Add(c.Balance, amount)) +func (c *StateObject) AddBalance(amount *big.Int) { + c.SetBalance(new(big.Int).Add(c.balance, amount)) - statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.Balance, amount) + statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.balance, amount) } +func (c *StateObject) AddAmount(amount *big.Int) { c.AddBalance(amount) } -func (c *StateObject) SubAmount(amount *big.Int) { - c.SetBalance(new(big.Int).Sub(c.Balance, amount)) +func (c *StateObject) SubBalance(amount *big.Int) { + c.SetBalance(new(big.Int).Sub(c.balance, amount)) - statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.Balance, amount) + statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.balance, amount) } +func (c *StateObject) SubAmount(amount *big.Int) { c.SubBalance(amount) } func (c *StateObject) SetBalance(amount *big.Int) { - c.Balance = amount + c.balance = amount } +func (self *StateObject) Balance() *big.Int { return self.balance } + // // Gas setters and getters // @@ -198,8 +202,8 @@ func (c *StateObject) SetBalance(amount *big.Int) { func (c *StateObject) ReturnGas(gas, price *big.Int) {} func (c *StateObject) ConvertGas(gas, price *big.Int) error { total := new(big.Int).Mul(gas, price) - if total.Cmp(c.Balance) > 0 { - return fmt.Errorf("insufficient amount: %v, %v", c.Balance, total) + if total.Cmp(c.balance) > 0 { + return fmt.Errorf("insufficient amount: %v, %v", c.balance, total) } c.SubAmount(total) @@ -232,12 +236,12 @@ func (self *StateObject) RefundGas(gas, price *big.Int) { rGas := new(big.Int).Set(gas) rGas.Mul(rGas, price) - self.Balance.Sub(self.Balance, rGas) + self.balance.Sub(self.balance, rGas) } func (self *StateObject) Copy() *StateObject { stateObject := NewStateObject(self.Address()) - stateObject.Balance.Set(self.Balance) + stateObject.balance.Set(self.balance) stateObject.codeHash = ethutil.CopyBytes(self.codeHash) stateObject.Nonce = self.Nonce if self.State != nil { @@ -281,7 +285,7 @@ func (self *StateObject) Object() *StateObject { // Debug stuff func (self *StateObject) CreateOutputForDiff() { - fmt.Printf("%x %x %x %x\n", self.Address(), self.State.Root(), self.Balance.Bytes(), self.Nonce) + fmt.Printf("%x %x %x %x\n", self.Address(), self.State.Root(), self.balance.Bytes(), self.Nonce) self.EachStorage(func(addr string, value *ethutil.Value) { fmt.Printf("%x %x\n", addr, value.Bytes()) }) @@ -300,7 +304,7 @@ func (c *StateObject) RlpEncode() []byte { root = "" } - return ethutil.Encode([]interface{}{c.Nonce, c.Balance, root, c.CodeHash()}) + return ethutil.Encode([]interface{}{c.Nonce, c.balance, root, c.CodeHash()}) } func (c *StateObject) CodeHash() ethutil.Bytes { @@ -316,7 +320,7 @@ func (c *StateObject) RlpDecode(data []byte) { decoder := ethutil.NewValueFromBytes(data) c.Nonce = decoder.Get(0).Uint() - c.Balance = decoder.Get(1).BigInt() + c.balance = decoder.Get(1).BigInt() c.State = New(ethtrie.New(ethutil.Config.Db, decoder.Get(2).Interface())) c.storage = make(map[string]*ethutil.Value) c.gasPool = new(big.Int) diff --git a/peer.go b/peer.go index 04ff4af39..557c436f6 100644 --- a/peer.go +++ b/peer.go @@ -674,7 +674,7 @@ func (p *Peer) pushPeers() { func (self *Peer) pushStatus() { msg := ethwire.NewMessage(ethwire.MsgStatusTy, []interface{}{ - //uint32(ProtocolVersion), + uint32(ProtocolVersion), uint32(NetVersion), self.ethereum.ChainManager().TD, self.ethereum.ChainManager().CurrentBlock.Hash(), diff --git a/tests/helper/vm.go b/tests/helper/vm.go index a3d54de23..06c3d4eca 100644 --- a/tests/helper/vm.go +++ b/tests/helper/vm.go @@ -50,11 +50,14 @@ func (self *Env) Difficulty() *big.Int { return self.difficulty } func (self *Env) BlockHash() []byte { return nil } func (self *Env) State() *ethstate.State { return self.state } func (self *Env) GasLimit() *big.Int { return self.gasLimit } +func (self *Env) Transfer(from, to vm.Account, amount *big.Int) error { + return nil +} func RunVm(state *ethstate.State, env, exec map[string]string) ([]byte, *big.Int, error) { address := FromHex(exec["address"]) caller := state.GetOrNewStateObject(FromHex(exec["caller"])) - caller.Balance = ethutil.Big(exec["value"]) + caller.SetBalance(ethutil.Big(exec["value"])) evm := vm.New(NewEnvFromMap(state, env, exec), vm.DebugVmTy) diff --git a/tests/vm/gh_test.go b/tests/vm/gh_test.go index f27cc7af3..64f279d8d 100644 --- a/tests/vm/gh_test.go +++ b/tests/vm/gh_test.go @@ -18,7 +18,7 @@ type Account struct { func StateObjectFromAccount(addr string, account Account) *ethstate.StateObject { obj := ethstate.NewStateObject(ethutil.Hex2Bytes(addr)) - obj.Balance = ethutil.Big(account.Balance) + obj.SetBalance(ethutil.Big(account.Balance)) if ethutil.IsHex(account.Code) { account.Code = account.Code[2:] @@ -44,9 +44,6 @@ func RunVmTest(p string, t *testing.T) { helper.CreateFileTests(t, p, &tests) for name, test := range tests { - if name != "CallRecursiveBomb" { - continue - } state := ethstate.New(helper.NewTrie()) for addr, account := range test.Pre { obj := StateObjectFromAccount(addr, account) @@ -92,7 +89,6 @@ func TestVMArithmetic(t *testing.T) { } func TestVMSystemOperation(t *testing.T) { - helper.Logger.SetLogLevel(5) const fn = "../files/vmtests/vmSystemOperationsTest.json" RunVmTest(fn, t) } diff --git a/vm/environment.go b/vm/environment.go index 2d933b65c..23b46c5df 100644 --- a/vm/environment.go +++ b/vm/environment.go @@ -1,6 +1,7 @@ package vm import ( + "errors" "math/big" "github.com/ethereum/eth-go/ethstate" @@ -18,9 +19,28 @@ type Environment interface { Difficulty() *big.Int BlockHash() []byte GasLimit() *big.Int + Transfer(from, to Account, amount *big.Int) error } type Object interface { GetStorage(key *big.Int) *ethutil.Value SetStorage(key *big.Int, value *ethutil.Value) } + +type Account interface { + SubBalance(amount *big.Int) + AddBalance(amount *big.Int) + Balance() *big.Int +} + +// generic transfer method +func Transfer(from, to Account, amount *big.Int) error { + if from.Balance().Cmp(amount) < 0 { + return errors.New("Insufficient balance in account") + } + + from.SubBalance(amount) + to.AddBalance(amount) + + return nil +} diff --git a/vm/execution.go b/vm/execution.go index 6bed43026..4c4bd1e3c 100644 --- a/vm/execution.go +++ b/vm/execution.go @@ -48,17 +48,17 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, Value: self.value, }) - object := caller.Object() - if object.Balance.Cmp(self.value) < 0 { + from, to := caller.Object(), env.State().GetOrNewStateObject(self.address) + err = env.Transfer(from, to, self.value) + if err != nil { caller.ReturnGas(self.Gas, self.price) - err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, object.Balance) + err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance) } else { - stateObject := env.State().GetOrNewStateObject(self.address) - self.object = stateObject + self.object = to - caller.Object().SubAmount(self.value) - stateObject.AddAmount(self.value) + //caller.Object().SubAmount(self.value) + //stateObject.AddAmount(self.value) // Pre-compiled contracts (address.go) 1, 2 & 3. naddr := ethutil.BigD(caddr).Uint64() @@ -69,7 +69,7 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, } } else { // Create a new callable closure - c := NewClosure(msg, caller, stateObject, code, self.Gas, self.price) + c := NewClosure(msg, caller, to, code, self.Gas, self.price) c.exe = self if self.vm.Depth() == MaxCallDepth { diff --git a/vm/vm.go b/vm/vm.go index 72d4f7131..b5c7c0e21 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -692,7 +692,7 @@ func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) { receiver := self.env.State().GetOrNewStateObject(stack.Pop().Bytes()) - receiver.AddAmount(closure.object.Balance) + receiver.AddAmount(closure.object.Balance()) closure.object.MarkForDeletion() -- cgit v1.2.3 From 51ecab6967a15b82f9285cd0ffd3352607dc8612 Mon Sep 17 00:00:00 2001 From: obscuren Date: Wed, 22 Oct 2014 23:39:15 +0200 Subject: Do not set error on recover --- vm/vm_debug.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'vm') diff --git a/vm/vm_debug.go b/vm/vm_debug.go index 8773df087..acdeb4be9 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -82,7 +82,8 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Endl() ret = closure.Return(nil) - err = fmt.Errorf("%v", r) + // No error should be set. Recover is used with require + // Is this too error prone? } }() } @@ -106,7 +107,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { step++ // Get the memory location of pc - op := OpCode(closure.Get(pc).Uint()) + op = OpCode(closure.Get(pc).Uint()) // XXX Leave this Println intact. Don't change this to the log system. // Used for creating diffs between implementations -- cgit v1.2.3 From 29b8a0bc5ffa7a674a06a211e1c8bdd1b6ed07b1 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 23 Oct 2014 01:01:26 +0200 Subject: Updated the VM & VM tests * Stack Error shouldn't revert to previous state * Updated VM Test tool * Added Transfer method to VM Env --- ethchain/chain_manager.go | 2 +- ethchain/state_transition.go | 23 +++++------------------ ethchain/transaction_pool.go | 2 +- ethchain/vm_env.go | 4 ++++ ethpipe/js_pipe.go | 2 +- ethpipe/vm_env.go | 4 ++++ rpc/packages.go | 2 +- tests/ethtest/main.go | 2 +- tests/helper/vm.go | 5 ++--- tests/vm/gh_test.go | 1 + vm/common.go | 2 +- vm/execution.go | 14 +++++++------- vm/types.go | 2 -- vm/vm.go | 4 ---- vm/vm_debug.go | 5 +---- 15 files changed, 30 insertions(+), 44 deletions(-) (limited to 'vm') diff --git a/ethchain/chain_manager.go b/ethchain/chain_manager.go index 227b02c0a..9f82eae41 100644 --- a/ethchain/chain_manager.go +++ b/ethchain/chain_manager.go @@ -162,7 +162,7 @@ func AddTestNetFunds(block *Block) { } { codedAddr := ethutil.Hex2Bytes(addr) account := block.state.GetAccount(codedAddr) - account.Balance = ethutil.Big("1606938044258990275541962092341162602522202993782792835301376") //ethutil.BigPow(2, 200) + account.SetBalance(ethutil.Big("1606938044258990275541962092341162602522202993782792835301376")) //ethutil.BigPow(2, 200) block.state.UpdateStateObject(account) } } diff --git a/ethchain/state_transition.go b/ethchain/state_transition.go index 79321eaac..1e6834729 100644 --- a/ethchain/state_transition.go +++ b/ethchain/state_transition.go @@ -89,8 +89,8 @@ func (self *StateTransition) BuyGas() error { var err error sender := self.Sender() - if sender.Balance.Cmp(self.tx.GasValue()) < 0 { - return fmt.Errorf("Insufficient funds to pre-pay gas. Req %v, has %v", self.tx.GasValue(), sender.Balance) + if sender.Balance().Cmp(self.tx.GasValue()) < 0 { + return fmt.Errorf("Insufficient funds to pre-pay gas. Req %v, has %v", self.tx.GasValue(), sender.Balance()) } coinbase := self.Coinbase() @@ -171,7 +171,7 @@ func (self *StateTransition) TransitionState() (err error) { return } - if sender.Balance.Cmp(self.value) < 0 { + if sender.Balance().Cmp(self.value) < 0 { return fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, sender.Balance) } @@ -243,19 +243,6 @@ func (self *StateTransition) TransitionState() (err error) { return } -func (self *StateTransition) transferValue(sender, receiver *ethstate.StateObject) error { - if sender.Balance.Cmp(self.value) < 0 { - return fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, sender.Balance) - } - - // Subtract the amount from the senders account - sender.SubAmount(self.value) - // Add the amount to receivers account which should conclude this transaction - receiver.AddAmount(self.value) - - return nil -} - func (self *StateTransition) Eval(msg *ethstate.Message, script []byte, context *ethstate.StateObject) (ret []byte, err error) { var ( transactor = self.Sender() @@ -265,9 +252,9 @@ func (self *StateTransition) Eval(msg *ethstate.Message, script []byte, context ) //vm := vm.New(env, vm.Type(ethutil.Config.VmType)) - vm := vm.New(env, vm.DebugVmTy) + evm := vm.New(env, vm.DebugVmTy) - ret, _, err = callerClosure.Call(vm, self.tx.Data) + ret, _, err = callerClosure.Call(evm, self.tx.Data) return } diff --git a/ethchain/transaction_pool.go b/ethchain/transaction_pool.go index ff3184582..0ddc4e435 100644 --- a/ethchain/transaction_pool.go +++ b/ethchain/transaction_pool.go @@ -117,7 +117,7 @@ func (pool *TxPool) ValidateTransaction(tx *Transaction) error { totAmount := new(big.Int).Set(tx.Value) // Make sure there's enough in the sender's account. Having insufficient // funds won't invalidate this transaction but simple ignores it. - if sender.Balance.Cmp(totAmount) < 0 { + if sender.Balance().Cmp(totAmount) < 0 { return fmt.Errorf("[TXPL] Insufficient amount in sender's (%x) account", tx.Sender()) } diff --git a/ethchain/vm_env.go b/ethchain/vm_env.go index 4600878d1..36c9d6002 100644 --- a/ethchain/vm_env.go +++ b/ethchain/vm_env.go @@ -4,6 +4,7 @@ import ( "math/big" "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/vm" ) type VMEnv struct { @@ -30,3 +31,6 @@ func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } func (self *VMEnv) Value() *big.Int { return self.tx.Value } func (self *VMEnv) State() *ethstate.State { return self.state } func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } +func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error { + return vm.Transfer(from, to, amount) +} diff --git a/ethpipe/js_pipe.go b/ethpipe/js_pipe.go index 873373b75..7eb33b4ea 100644 --- a/ethpipe/js_pipe.go +++ b/ethpipe/js_pipe.go @@ -98,7 +98,7 @@ func (self *JSPipe) StorageAt(addr, storageAddr string) string { } func (self *JSPipe) BalanceAt(addr string) string { - return self.World().SafeGet(ethutil.Hex2Bytes(addr)).Balance.String() + return self.World().SafeGet(ethutil.Hex2Bytes(addr)).Balance().String() } func (self *JSPipe) TxCountAt(address string) int { diff --git a/ethpipe/vm_env.go b/ethpipe/vm_env.go index 10ce0e561..7ef335800 100644 --- a/ethpipe/vm_env.go +++ b/ethpipe/vm_env.go @@ -5,6 +5,7 @@ import ( "github.com/ethereum/eth-go/ethchain" "github.com/ethereum/eth-go/ethstate" + "github.com/ethereum/eth-go/vm" ) type VMEnv struct { @@ -33,3 +34,6 @@ func (self *VMEnv) BlockHash() []byte { return self.block.Hash() } func (self *VMEnv) Value() *big.Int { return self.value } func (self *VMEnv) State() *ethstate.State { return self.state } func (self *VMEnv) GasLimit() *big.Int { return self.block.GasLimit } +func (self *VMEnv) Transfer(from, to vm.Account, amount *big.Int) error { + return vm.Transfer(from, to, amount) +} diff --git a/rpc/packages.go b/rpc/packages.go index d8dae003f..3fba7ae4f 100644 --- a/rpc/packages.go +++ b/rpc/packages.go @@ -296,7 +296,7 @@ func (p *EthereumApi) GetBalanceAt(args *GetBalanceArgs, reply *string) error { return err } state := p.pipe.World().SafeGet(ethutil.Hex2Bytes(args.Address)) - *reply = NewSuccessRes(BalanceRes{Balance: state.Balance.String(), Address: args.Address}) + *reply = NewSuccessRes(BalanceRes{Balance: state.Balance().String(), Address: args.Address}) return nil } diff --git a/tests/ethtest/main.go b/tests/ethtest/main.go index 3e85891e4..e19892557 100644 --- a/tests/ethtest/main.go +++ b/tests/ethtest/main.go @@ -22,7 +22,7 @@ type Account struct { func StateObjectFromAccount(addr string, account Account) *ethstate.StateObject { obj := ethstate.NewStateObject(ethutil.Hex2Bytes(addr)) - obj.Balance = ethutil.Big(account.Balance) + obj.SetBalance(ethutil.Big(account.Balance)) if ethutil.IsHex(account.Code) { account.Code = account.Code[2:] diff --git a/tests/helper/vm.go b/tests/helper/vm.go index 06c3d4eca..f70ce48a6 100644 --- a/tests/helper/vm.go +++ b/tests/helper/vm.go @@ -51,17 +51,16 @@ func (self *Env) BlockHash() []byte { return nil } func (self *Env) State() *ethstate.State { return self.state } func (self *Env) GasLimit() *big.Int { return self.gasLimit } func (self *Env) Transfer(from, to vm.Account, amount *big.Int) error { - return nil + return vm.Transfer(from, to, amount) } func RunVm(state *ethstate.State, env, exec map[string]string) ([]byte, *big.Int, error) { address := FromHex(exec["address"]) caller := state.GetOrNewStateObject(FromHex(exec["caller"])) - caller.SetBalance(ethutil.Big(exec["value"])) evm := vm.New(NewEnvFromMap(state, env, exec), vm.DebugVmTy) - execution := vm.NewExecution(evm, address, FromHex(exec["data"]), ethutil.Big(exec["gas"]), ethutil.Big(exec["gasPrice"]), ethutil.Big(exec["value"])) + execution.SkipTransfer = true ret, err := execution.Exec(address, caller) return ret, execution.Gas, err diff --git a/tests/vm/gh_test.go b/tests/vm/gh_test.go index 64f279d8d..a86831d9e 100644 --- a/tests/vm/gh_test.go +++ b/tests/vm/gh_test.go @@ -89,6 +89,7 @@ func TestVMArithmetic(t *testing.T) { } func TestVMSystemOperation(t *testing.T) { + //helper.Logger.SetLogLevel(5) const fn = "../files/vmtests/vmSystemOperationsTest.json" RunVmTest(fn, t) } diff --git a/vm/common.go b/vm/common.go index 6921b38ff..3d9f57290 100644 --- a/vm/common.go +++ b/vm/common.go @@ -39,7 +39,7 @@ var ( S256 = ethutil.S256 ) -const MaxCallDepth = 1024 +const MaxCallDepth = 1025 func calcMemSize(off, l *big.Int) *big.Int { if l.Cmp(ethutil.Big0) == 0 { diff --git a/vm/execution.go b/vm/execution.go index 4c4bd1e3c..bd174d64e 100644 --- a/vm/execution.go +++ b/vm/execution.go @@ -13,6 +13,7 @@ type Execution struct { address, input []byte Gas, price, value *big.Int object *ethstate.StateObject + SkipTransfer bool } func NewExecution(vm VirtualMachine, address, input []byte, gas, gasPrice, value *big.Int) *Execution { @@ -49,17 +50,17 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, }) from, to := caller.Object(), env.State().GetOrNewStateObject(self.address) - err = env.Transfer(from, to, self.value) + // Skipping transfer is used on testing for the initial call + if !self.SkipTransfer { + err = env.Transfer(from, to, self.value) + } + if err != nil { caller.ReturnGas(self.Gas, self.price) err = fmt.Errorf("Insufficient funds to transfer value. Req %v, has %v", self.value, from.Balance) } else { self.object = to - - //caller.Object().SubAmount(self.value) - //stateObject.AddAmount(self.value) - // Pre-compiled contracts (address.go) 1, 2 & 3. naddr := ethutil.BigD(caddr).Uint64() if p := Precompiled[naddr]; p != nil { @@ -73,14 +74,13 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, c.exe = self if self.vm.Depth() == MaxCallDepth { - c.UseGas(c.Gas) + c.UseGas(self.Gas) return c.Return(nil), fmt.Errorf("Max call depth exceeded (%d)", MaxCallDepth) } // Executer the closure and get the return value (if any) ret, _, err = c.Call(self.vm, self.input) - msg.Output = ret } } diff --git a/vm/types.go b/vm/types.go index 5fd92052b..6fb9a5c95 100644 --- a/vm/types.go +++ b/vm/types.go @@ -151,7 +151,6 @@ const ( CALLCODE = 0xf3 // 0x70 range - other - LOG = 0xfe // XXX Unofficial SUICIDE = 0xff ) @@ -300,7 +299,6 @@ var opCodeToString = map[OpCode]string{ CALLCODE: "CALLCODE", // 0x70 range - other - LOG: "LOG", SUICIDE: "SUICIDE", } diff --git a/vm/vm.go b/vm/vm.go index b5c7c0e21..1a7a40a36 100644 --- a/vm/vm.go +++ b/vm/vm.go @@ -660,8 +660,6 @@ func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) { // Get the arguments from the memory args := mem.Get(inOffset.Int64(), inSize.Int64()) - //snapshot := self.env.State().Copy() - var executeAddr []byte if op == CALLCODE { executeAddr = closure.Address() @@ -673,8 +671,6 @@ func (self *Vm) RunClosure(closure *Closure) (ret []byte, err error) { ret, err := msg.Exec(addr.Bytes(), closure) if err != nil { stack.Push(ethutil.BigFalse) - - //self.env.State().Set(snapshot) } else { stack.Push(ethutil.BigTrue) diff --git a/vm/vm_debug.go b/vm/vm_debug.go index acdeb4be9..ba1781109 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -237,10 +237,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { mem.Resize(newMemSize.Uint64()) switch op { - case LOG: - stack.Print() - mem.Print() - // 0x20 range + // 0x20 range case ADD: require(2) x, y := stack.Popn() -- cgit v1.2.3 From 06aa74e7df49969fc181ecfcf5652263d74624f5 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 23 Oct 2014 10:14:55 +0200 Subject: All Stack requirements are now checked prior to reduring gas. --- vm/vm_debug.go | 56 +++++++++++++++++++------------------------------------- 1 file changed, 19 insertions(+), 37 deletions(-) (limited to 'vm') diff --git a/vm/vm_debug.go b/vm/vm_debug.go index ba1781109..fe004046c 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -138,13 +138,31 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { addStepGasUsage(GasStep) var newMemSize *big.Int = ethutil.Big0 + // Stack Check, memory resize & gas phase switch op { + // Stack checks only + case NOT, CALLDATALOAD, POP, JUMP, NEG: // 1 + require(1) + case ADD, SUB, DIV, SDIV, MOD, SMOD, EXP, LT, GT, SLT, SGT, EQ, AND, OR, XOR, BYTE: // 2 + require(2) + case ADDMOD, MULMOD: // 3 + require(3) + case SWAP1, SWAP2, SWAP3, SWAP4, SWAP5, SWAP6, SWAP7, SWAP8, SWAP9, SWAP10, SWAP11, SWAP12, SWAP13, SWAP14, SWAP15, SWAP16: + n := int(op - SWAP1 + 2) + require(n) + case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16: + n := int(op - DUP1 + 1) + require(n) + // Gas only case STOP: gas.Set(ethutil.Big0) case SUICIDE: + require(1) + gas.Set(ethutil.Big0) case SLOAD: gas.Set(GasSLoad) + // Memory resize & Gas case SSTORE: var mult *big.Int y, x := stack.Peekn() @@ -158,6 +176,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { } gas = new(big.Int).Mul(mult, GasSStore) case BALANCE: + require(1) gas.Set(GasBalance) case MSTORE: require(2) @@ -239,7 +258,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { switch op { // 0x20 range case ADD: - require(2) x, y := stack.Popn() self.Printf(" %v + %v", y, x) @@ -251,7 +269,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // Pop result back on the stack stack.Push(base) case SUB: - require(2) x, y := stack.Popn() self.Printf(" %v - %v", y, x) @@ -263,7 +280,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // Pop result back on the stack stack.Push(base) case MUL: - require(2) x, y := stack.Popn() self.Printf(" %v * %v", y, x) @@ -275,7 +291,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // Pop result back on the stack stack.Push(base) case DIV: - require(2) x, y := stack.Pop(), stack.Pop() self.Printf(" %v / %v", x, y) @@ -289,7 +304,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // Pop result back on the stack stack.Push(base) case SDIV: - require(2) x, y := S256(stack.Pop()), S256(stack.Pop()) self.Printf(" %v / %v", x, y) @@ -312,7 +326,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" = %v", base) stack.Push(base) case MOD: - require(2) x, y := stack.Pop(), stack.Pop() self.Printf(" %v %% %v", x, y) @@ -328,7 +341,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" = %v", base) stack.Push(base) case SMOD: - require(2) x, y := S256(stack.Pop()), S256(stack.Pop()) self.Printf(" %v %% %v", x, y) @@ -352,7 +364,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(base) case EXP: - require(2) x, y := stack.Popn() self.Printf(" %v ** %v", y, x) @@ -365,14 +376,12 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(base) case NEG: - require(1) base.Sub(Pow256, stack.Pop()) base = U256(base) stack.Push(base) case LT: - require(2) x, y := stack.Popn() self.Printf(" %v < %v", y, x) // x < y @@ -382,7 +391,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(ethutil.BigFalse) } case GT: - require(2) x, y := stack.Popn() self.Printf(" %v > %v", y, x) @@ -394,7 +402,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { } case SLT: - require(2) y, x := S256(stack.Pop()), S256(stack.Pop()) self.Printf(" %v < %v", y, x) // x < y @@ -404,7 +411,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(ethutil.BigFalse) } case SGT: - require(2) y, x := S256(stack.Pop()), S256(stack.Pop()) self.Printf(" %v > %v", y, x) @@ -416,7 +422,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { } case EQ: - require(2) x, y := stack.Popn() self.Printf(" %v == %v", y, x) @@ -427,7 +432,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(ethutil.BigFalse) } case NOT: - require(1) x := stack.Pop() if x.Cmp(ethutil.BigFalse) > 0 { stack.Push(ethutil.BigFalse) @@ -437,25 +441,21 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // 0x10 range case AND: - require(2) x, y := stack.Popn() self.Printf(" %v & %v", y, x) stack.Push(base.And(y, x)) case OR: - require(2) x, y := stack.Popn() self.Printf(" %v | %v", y, x) stack.Push(base.Or(y, x)) case XOR: - require(2) x, y := stack.Popn() self.Printf(" %v ^ %v", y, x) stack.Push(base.Xor(y, x)) case BYTE: - require(2) val, th := stack.Popn() if th.Cmp(big.NewInt(32)) < 0 { @@ -470,7 +470,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(base) case ADDMOD: - require(3) x := stack.Pop() y := stack.Pop() @@ -485,7 +484,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(base) case MULMOD: - require(3) x := stack.Pop() y := stack.Pop() @@ -502,7 +500,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { // 0x20 range case SHA3: - require(2) size, offset := stack.Popn() data := ethcrypto.Sha3(mem.Get(offset.Int64(), size.Int64())) @@ -515,7 +512,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => %x", closure.Address()) case BALANCE: - require(1) addr := stack.Pop().Bytes() balance := state.GetBalance(addr) @@ -541,7 +537,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => %v", value) case CALLDATALOAD: - require(1) var ( offset = stack.Pop() data = make([]byte, 32) @@ -675,7 +670,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => 0x%x", data.Bytes()) case POP: - require(1) stack.Pop() case DUP1, DUP2, DUP3, DUP4, DUP5, DUP6, DUP7, DUP8, DUP9, DUP10, DUP11, DUP12, DUP13, DUP14, DUP15, DUP16: n := int(op - DUP1 + 1) @@ -692,21 +686,18 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => [%d] %x [0] %x", n, x.Bytes(), y.Bytes()) case MLOAD: - require(1) offset := stack.Pop() val := ethutil.BigD(mem.Get(offset.Int64(), 32)) stack.Push(val) self.Printf(" => 0x%x", val.Bytes()) case MSTORE: // Store the value at stack top-1 in to memory at location stack top - require(2) // Pop value of the stack val, mStart := stack.Popn() mem.Set(mStart.Int64(), 32, ethutil.BigToBytes(val, 256)) self.Printf(" => 0x%x", val) case MSTORE8: - require(2) off := stack.Pop() val := stack.Pop() @@ -714,14 +705,12 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" => [%v] 0x%x", off, val) case SLOAD: - require(1) loc := stack.Pop() val := ethutil.BigD(state.GetState(closure.Address(), loc.Bytes())) stack.Push(val) self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) case SSTORE: - require(2) val, loc := stack.Popn() state.SetState(closure.Address(), loc.Bytes(), val) @@ -732,13 +721,11 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Printf(" {0x%x : 0x%x}", loc.Bytes(), val.Bytes()) case JUMP: - require(1) jump(stack.Pop()) continue case JUMPI: - require(2) cond, pos := stack.Popn() if cond.Cmp(ethutil.BigTrue) >= 0 { @@ -756,7 +743,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { stack.Push(closure.Gas) // 0x60 range case CREATE: - require(3) var ( err error @@ -801,8 +787,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { self.Dbg.SetCode(closure.Code) } case CALL, CALLCODE: - require(7) - self.Endl() gas := stack.Pop() @@ -842,7 +826,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { } case RETURN: - require(2) size, offset := stack.Popn() ret := mem.Get(offset.Int64(), size.Int64()) @@ -850,7 +833,6 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { return closure.Return(ret), nil case SUICIDE: - require(1) receiver := state.GetOrNewStateObject(stack.Pop().Bytes()) -- cgit v1.2.3 From feef194829b07570e91873ed5d1e8cc51e8fa430 Mon Sep 17 00:00:00 2001 From: obscuren Date: Thu, 23 Oct 2014 14:04:00 +0200 Subject: Chnged to use GetOp instead & added error + checking --- tests/ethtest/main.go | 3 ++- vm/errors.go | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ vm/execution.go | 4 ++-- vm/vm_debug.go | 6 +++--- 4 files changed, 58 insertions(+), 6 deletions(-) create mode 100644 vm/errors.go (limited to 'vm') diff --git a/tests/ethtest/main.go b/tests/ethtest/main.go index e19892557..1f2a15e1c 100644 --- a/tests/ethtest/main.go +++ b/tests/ethtest/main.go @@ -63,7 +63,7 @@ func RunVmTest(js string) (failed int) { // When an error is returned it doesn't always mean the tests fails. // Have to come up with some conditional failing mechanism. if err != nil { - helper.Log.Infoln(err) + log.Println(err) } rexp := helper.FromHex(test.Out) @@ -96,6 +96,7 @@ func RunVmTest(js string) (failed int) { } func main() { + helper.Logger.SetLogLevel(5) if len(os.Args) == 1 { log.Fatalln("no json supplied") } diff --git a/vm/errors.go b/vm/errors.go new file mode 100644 index 000000000..ab011bd62 --- /dev/null +++ b/vm/errors.go @@ -0,0 +1,51 @@ +package vm + +import ( + "fmt" + "math/big" +) + +type OutOfGasError struct { + req, has *big.Int +} + +func OOG(req, has *big.Int) OutOfGasError { + return OutOfGasError{req, has} +} + +func (self OutOfGasError) Error() string { + return fmt.Sprintf("out of gas! require %v, have %v", self.req, self.has) +} + +func IsOOGErr(err error) bool { + _, ok := err.(OutOfGasError) + return ok +} + +type StackError struct { + req, has int +} + +func StackErr(req, has int) StackError { + return StackError{req, has} +} + +func (self StackError) Error() string { + return fmt.Sprintf("stack error! require %v, have %v", self.req, self.has) +} + +func IsStack(err error) bool { + _, ok := err.(StackError) + return ok +} + +type DepthError struct{} + +func (self DepthError) Error() string { + return fmt.Sprintf("Max call depth exceeded (%d)", MaxCallDepth) +} + +func IsDepthErr(err error) bool { + _, ok := err.(DepthError) + return ok +} diff --git a/vm/execution.go b/vm/execution.go index bd174d64e..c518c4b57 100644 --- a/vm/execution.go +++ b/vm/execution.go @@ -36,7 +36,7 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, snapshot := env.State().Copy() defer func() { - if err != nil { + if IsDepthErr(err) || IsOOGErr(err) { env.State().Set(snapshot) } }() @@ -76,7 +76,7 @@ func (self *Execution) exec(code, caddr []byte, caller ClosureRef) (ret []byte, if self.vm.Depth() == MaxCallDepth { c.UseGas(self.Gas) - return c.Return(nil), fmt.Errorf("Max call depth exceeded (%d)", MaxCallDepth) + return c.Return(nil), DepthError{} } // Executer the closure and get the return value (if any) diff --git a/vm/vm_debug.go b/vm/vm_debug.go index fe004046c..b44604121 100644 --- a/vm/vm_debug.go +++ b/vm/vm_debug.go @@ -107,7 +107,7 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { step++ // Get the memory location of pc - op = OpCode(closure.Get(pc).Uint()) + op = closure.GetOp(int(pc.Uint64())) // XXX Leave this Println intact. Don't change this to the log system. // Used for creating diffs between implementations @@ -246,11 +246,11 @@ func (self *DebugVm) RunClosure(closure *Closure) (ret []byte, err error) { if !closure.UseGas(gas) { self.Endl() - err := fmt.Errorf("Insufficient gas for %v. req %v has %v", op, gas, closure.Gas) + tmp := new(big.Int).Set(closure.Gas) closure.UseGas(closure.Gas) - return closure.Return(nil), err + return closure.Return(nil), OOG(gas, tmp) } mem.Resize(newMemSize.Uint64()) -- cgit v1.2.3