context.go 1.85 KB
Newer Older
obscuren's avatar
obscuren committed
1
package vm
2 3

import (
obscuren's avatar
obscuren committed
4 5
	"math/big"

obscuren's avatar
obscuren committed
6
	"github.com/ethereum/go-ethereum/common"
7 8
)

obscuren's avatar
obscuren committed
9
type ContextRef interface {
10
	ReturnGas(*big.Int, *big.Int)
obscuren's avatar
obscuren committed
11
	Address() common.Address
12
	SetCode([]byte)
13 14
}

obscuren's avatar
obscuren committed
15
type Context struct {
obscuren's avatar
obscuren committed
16
	caller ContextRef
17
	self   ContextRef
18

19
	Code     []byte
obscuren's avatar
obscuren committed
20
	CodeAddr *common.Address
21 22

	value, Gas, UsedGas, Price *big.Int
23 24 25 26

	Args []byte
}

obscuren's avatar
obscuren committed
27
// Create a new context for the given data items
28 29
func NewContext(caller ContextRef, object ContextRef, value, gas, price *big.Int) *Context {
	c := &Context{caller: caller, self: object, Args: nil}
30 31 32 33

	// 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)
34
	c.value = new(big.Int).Set(value)
35 36 37 38 39 40 41 42
	// 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
}

obscuren's avatar
obscuren committed
43
func (c *Context) GetOp(n *big.Int) OpCode {
obscuren's avatar
obscuren committed
44
	return OpCode(c.GetByte(n))
45 46
}

obscuren's avatar
obscuren committed
47 48 49
func (c *Context) GetByte(n *big.Int) byte {
	if n.Cmp(big.NewInt(int64(len(c.Code)))) < 0 {
		return c.Code[n.Int64()]
50 51 52 53 54
	}

	return 0
}

obscuren's avatar
obscuren committed
55
func (c *Context) Return(ret []byte) []byte {
56 57 58 59 60 61
	// Return the remaining gas to the caller
	c.caller.ReturnGas(c.Gas, c.Price)

	return ret
}

62 63 64
/*
 * Gas functions
 */
obscuren's avatar
obscuren committed
65 66 67 68
func (c *Context) UseGas(gas *big.Int) (ok bool) {
	ok = UseGas(c.Gas, gas)
	if ok {
		c.UsedGas.Add(c.UsedGas, gas)
69
	}
obscuren's avatar
obscuren committed
70
	return
71 72 73
}

// Implement the caller interface
obscuren's avatar
obscuren committed
74 75
func (c *Context) ReturnGas(gas, price *big.Int) {
	// Return the gas to the context
76 77 78 79
	c.Gas.Add(c.Gas, gas)
	c.UsedGas.Sub(c.UsedGas, gas)
}

80 81 82
/*
 * Set / Get
 */
obscuren's avatar
obscuren committed
83
func (c *Context) Address() common.Address {
84
	return c.self.Address()
85 86
}

obscuren's avatar
obscuren committed
87
func (self *Context) SetCode(code []byte) {
88 89
	self.Code = code
}
90

obscuren's avatar
obscuren committed
91
func (self *Context) SetCallCode(addr *common.Address, code []byte) {
92 93 94
	self.Code = code
	self.CodeAddr = addr
}