bsc/ethchain/closure.go

109 lines
2.3 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"
)
type Callee interface {
ReturnGas(*big.Int, *State)
Address() []byte
}
2014-04-09 19:27:54 +03:00
type Reference interface {
Callee
ethutil.RlpEncodable
GetMem(*big.Int) *ethutil.Value
SetMem(*big.Int, *ethutil.Value)
}
// Basic inline closure object which implement the 'closure' interface
type Closure struct {
callee Callee
2014-04-09 19:27:54 +03:00
object Reference
Script []byte
State *State
Gas *big.Int
2014-04-18 14:41:07 +03:00
Price *big.Int
Value *big.Int
Args []byte
}
// Create a new closure for the given data items
2014-04-18 14:41:07 +03:00
func NewClosure(callee Callee, object Reference, script []byte, state *State, gas, price, val *big.Int) *Closure {
return &Closure{callee, object, script, state, gas, price, val, nil}
}
// 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 19:27:54 +03: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 20:29:57 +03:00
if x.Int64() >= int64(len(c.Script)) || y.Int64() >= int64(len(c.Script)) {
2014-04-10 21:40:12 +03:00
return ethutil.NewValue(0)
}
2014-04-09 19:27:54 +03:00
partial := c.Script[x.Int64() : x.Int64()+y.Int64()]
return ethutil.NewValue(partial)
2014-04-09 15:08:18 +03:00
}
func (c *Closure) SetMem(x *big.Int, val *ethutil.Value) {
c.object.SetMem(x, val)
}
func (c *Closure) Address() []byte {
return c.object.Address()
}
2014-04-12 07:13:42 +03: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 {
c.callee.ReturnGas(c.Gas, c.State)
} else {
c.object.ReturnGas(c.Gas, c.State)
// TODO incase it's a POST contract we gotta serialise the contract again.
// But it's not yet defined
}
return ret
}
// Implement the Callee interface
func (c *Closure) ReturnGas(gas *big.Int, state *State) {
// Return the gas to the closure
c.Gas.Add(c.Gas, gas)
}
2014-04-09 19:27:54 +03:00
func (c *Closure) Object() Reference {
return c.object
}
func (c *Closure) Callee() Callee {
return c.callee
}