plugeth/ethchain/closure.go

113 lines
2.5 KiB
Go
Raw Normal View History

package ethchain
// TODO Re write VM to use values instead of big integers?
import (
"github.com/ethereum/eth-go/ethutil"
"math/big"
)
2014-04-27 14:50:44 +00:00
type ClosureRef interface {
ReturnGas(*big.Int, *big.Int, *State)
Address() []byte
GetMem(*big.Int) *ethutil.Value
SetStore(*big.Int, *ethutil.Value)
2014-04-27 14:50:44 +00:00
N() *big.Int
}
// Basic inline closure object which implement the 'closure' interface
type Closure struct {
callee *StateObject
object *StateObject
2014-04-09 16:27:54 +00:00
Script []byte
State *State
Gas *big.Int
2014-04-18 11:41:07 +00:00
Price *big.Int
Args []byte
}
// Create a new closure for the given data items
2014-05-08 12:20:45 +00:00
func NewClosure(callee, object *StateObject, script []byte, state *State, gas, price *big.Int) *Closure {
c := &Closure{callee: callee, object: object, Script: script, State: state, Args: nil}
// In most cases gas, price and value are pointers to transaction objects
// and we don't want the transaction's values to change.
c.Gas = new(big.Int).Set(gas)
c.Price = new(big.Int).Set(price)
return c
}
// Retuns the x element in data slice
func (c *Closure) GetMem(x *big.Int) *ethutil.Value {
m := c.object.GetMem(x)
if m == nil {
return ethutil.EmptyValue()
}
return m
}
2014-04-09 16:27:54 +00:00
func (c *Closure) Get(x *big.Int) *ethutil.Value {
return c.Gets(x, big.NewInt(1))
}
func (c *Closure) Gets(x, y *big.Int) *ethutil.Value {
2014-04-11 17:29:57 +00:00
if x.Int64() >= int64(len(c.Script)) || y.Int64() >= int64(len(c.Script)) {
2014-04-10 18:40:12 +00:00
return ethutil.NewValue(0)
}
2014-04-09 16:27:54 +00:00
partial := c.Script[x.Int64() : x.Int64()+y.Int64()]
return ethutil.NewValue(partial)
2014-04-09 12:08:18 +00:00
}
func (c *Closure) SetStorage(x *big.Int, val *ethutil.Value) {
c.object.SetStorage(x, val)
}
func (c *Closure) Address() []byte {
return c.object.Address()
}
2014-04-12 04:13:42 +00:00
type DebugHook func(step int, op OpCode, mem *Memory, stack *Stack)
func (c *Closure) Call(vm *Vm, args []byte, hook DebugHook) ([]byte, error) {
c.Args = args
return vm.RunClosure(c, hook)
}
func (c *Closure) Return(ret []byte) []byte {
// Return the remaining gas to the callee
// If no callee is present return it to
// the origin (i.e. contract or tx)
if c.callee != nil {
2014-04-19 23:31:01 +00:00
c.callee.ReturnGas(c.Gas, c.Price, c.State)
} else {
2014-04-19 23:31:01 +00:00
c.object.ReturnGas(c.Gas, c.Price, c.State)
}
return ret
}
// Implement the Callee interface
2014-04-19 23:31:01 +00:00
func (c *Closure) ReturnGas(gas, price *big.Int, state *State) {
// Return the gas to the closure
c.Gas.Add(c.Gas, gas)
}
func (c *Closure) Object() *StateObject {
return c.object
}
func (c *Closure) Callee() *StateObject {
return c.callee
}
2014-04-27 14:50:44 +00:00
func (c *Closure) N() *big.Int {
return c.object.N()
}