state_object.go 7.41 KB
Newer Older
obscuren's avatar
obscuren committed
1
package state
2 3

import (
4
	"bytes"
5
	"fmt"
6 7
	"math/big"

obscuren's avatar
obscuren committed
8
	"github.com/ethereum/go-ethereum/crypto"
9
	"github.com/ethereum/go-ethereum/ethutil"
10
	"github.com/ethereum/go-ethereum/rlp"
11
	"github.com/ethereum/go-ethereum/trie"
12 13 14 15 16
)

type Code []byte

func (self Code) String() string {
17
	return string(self) //strings.Join(Disassemble(self), " ")
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
}

type Storage map[string]*ethutil.Value

func (self Storage) Copy() Storage {
	cpy := make(Storage)
	for key, value := range self {
		// XXX Do we need a 'value' copy or is this sufficient?
		cpy[key] = value
	}

	return cpy
}

type StateObject struct {
33
	db ethutil.Database
34 35 36
	// Address of the object
	address []byte
	// Shared attributes
37
	balance  *big.Int
38
	codeHash []byte
39 40
	Nonce    uint64
	// Contract related attributes
obscuren's avatar
obscuren committed
41
	State    *StateDB
42
	Code     Code
43
	InitCode Code
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59

	storage Storage

	// Total gas pool is the total amount of gas currently
	// left if this object is the coinbase. Gas is directly
	// purchased of the coinbase.
	gasPool *big.Int

	// Mark for deletion
	// When an object is marked for deletion it will be delete from the trie
	// during the "update" phase of the state transition
	remove bool
}

func (self *StateObject) Reset() {
	self.storage = make(Storage)
60
	self.State.Reset()
61 62
}

63
func NewStateObject(addr []byte, db ethutil.Database) *StateObject {
64 65 66
	// This to ensure that it has 20 bytes (and not 0 bytes), thus left or right pad doesn't matter.
	address := ethutil.Address(addr)

67 68
	object := &StateObject{db: db, address: address, balance: new(big.Int), gasPool: new(big.Int)}
	object.State = New(nil, db) //New(trie.New(ethutil.Config.Db, ""))
69 70 71 72 73 74
	object.storage = make(Storage)
	object.gasPool = new(big.Int)

	return object
}

75
func NewStateObjectFromBytes(address, data []byte, db ethutil.Database) *StateObject {
76 77 78 79 80 81 82 83 84 85 86 87 88
	// TODO clean me up
	var extobject struct {
		Nonce    uint64
		Balance  *big.Int
		Root     []byte
		CodeHash []byte
	}
	err := rlp.Decode(bytes.NewReader(data), &extobject)
	if err != nil {
		fmt.Println(err)
		return nil
	}

89
	object := &StateObject{address: address, db: db}
90 91 92 93 94 95 96 97
	//object.RlpDecode(data)
	object.Nonce = extobject.Nonce
	object.balance = extobject.Balance
	object.codeHash = extobject.CodeHash
	object.State = New(extobject.Root, db)
	object.storage = make(map[string]*ethutil.Value)
	object.gasPool = new(big.Int)
	object.Code, _ = db.Get(extobject.CodeHash)
98 99 100 101 102 103

	return object
}

func (self *StateObject) MarkForDeletion() {
	self.remove = true
104
	statelogger.DebugDetailf("%x: #%d %v (deletion)\n", self.Address(), self.Nonce, self.balance)
105 106
}

obscuren's avatar
obscuren committed
107 108
func (c *StateObject) getAddr(addr []byte) *ethutil.Value {
	return ethutil.NewValueFromBytes([]byte(c.State.trie.Get(addr)))
109 110
}

obscuren's avatar
obscuren committed
111 112
func (c *StateObject) setAddr(addr []byte, value interface{}) {
	c.State.trie.Update(addr, ethutil.Encode(value))
113 114 115
}

func (self *StateObject) GetStorage(key *big.Int) *ethutil.Value {
obscuren's avatar
obscuren committed
116
	return self.GetState(key.Bytes())
117 118
}
func (self *StateObject) SetStorage(key *big.Int, value *ethutil.Value) {
obscuren's avatar
obscuren committed
119
	self.SetState(key.Bytes(), value)
120 121
}

122 123 124 125
func (self *StateObject) Storage() map[string]*ethutil.Value {
	return self.storage
}

obscuren's avatar
obscuren committed
126
func (self *StateObject) GetState(k []byte) *ethutil.Value {
127 128 129 130
	key := ethutil.LeftPadBytes(k, 32)

	value := self.storage[string(key)]
	if value == nil {
obscuren's avatar
obscuren committed
131
		value = self.getAddr(key)
132 133 134 135 136 137 138 139 140

		if !value.IsNil() {
			self.storage[string(key)] = value
		}
	}

	return value
}

obscuren's avatar
obscuren committed
141
func (self *StateObject) SetState(k []byte, value *ethutil.Value) {
142 143 144 145 146 147
	key := ethutil.LeftPadBytes(k, 32)
	self.storage[string(key)] = value.Copy()
}

func (self *StateObject) Sync() {
	for key, value := range self.storage {
obscuren's avatar
obscuren committed
148
		if value.Len() == 0 {
obscuren's avatar
obscuren committed
149
			self.State.trie.Delete([]byte(key))
150 151 152
			continue
		}

obscuren's avatar
obscuren committed
153
		self.setAddr([]byte(key), value)
154 155 156 157 158 159 160 161 162 163 164
	}
}

func (c *StateObject) GetInstr(pc *big.Int) *ethutil.Value {
	if int64(len(c.Code)-1) < pc.Int64() {
		return ethutil.NewValue(0)
	}

	return ethutil.NewValueFromBytes([]byte{c.Code[pc.Int64()]})
}

165 166
func (c *StateObject) AddBalance(amount *big.Int) {
	c.SetBalance(new(big.Int).Add(c.balance, amount))
167

168
	statelogger.Debugf("%x: #%d %v (+ %v)\n", c.Address(), c.Nonce, c.balance, amount)
169
}
170
func (c *StateObject) AddAmount(amount *big.Int) { c.AddBalance(amount) }
171

172 173
func (c *StateObject) SubBalance(amount *big.Int) {
	c.SetBalance(new(big.Int).Sub(c.balance, amount))
174

175
	statelogger.Debugf("%x: #%d %v (- %v)\n", c.Address(), c.Nonce, c.balance, amount)
176
}
177
func (c *StateObject) SubAmount(amount *big.Int) { c.SubBalance(amount) }
178

179
func (c *StateObject) SetBalance(amount *big.Int) {
180
	c.balance = amount
181 182
}

183 184
func (self *StateObject) Balance() *big.Int { return self.balance }

185 186 187 188 189 190 191 192
//
// Gas setters and getters
//

// Return the gas back to the origin. Used by the Virtual machine or Closures
func (c *StateObject) ReturnGas(gas, price *big.Int) {}
func (c *StateObject) ConvertGas(gas, price *big.Int) error {
	total := new(big.Int).Mul(gas, price)
193 194
	if total.Cmp(c.balance) > 0 {
		return fmt.Errorf("insufficient amount: %v, %v", c.balance, total)
195 196 197 198 199 200 201 202 203 204
	}

	c.SubAmount(total)

	return nil
}

func (self *StateObject) SetGasPool(gasLimit *big.Int) {
	self.gasPool = new(big.Int).Set(gasLimit)

205
	statelogger.Debugf("%x: gas (+ %v)", self.Address(), self.gasPool)
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
}

func (self *StateObject) BuyGas(gas, price *big.Int) error {
	if self.gasPool.Cmp(gas) < 0 {
		return GasLimitError(self.gasPool, gas)
	}

	rGas := new(big.Int).Set(gas)
	rGas.Mul(rGas, price)

	self.AddAmount(rGas)

	return nil
}

func (self *StateObject) RefundGas(gas, price *big.Int) {
	self.gasPool.Add(self.gasPool, gas)

	rGas := new(big.Int).Set(gas)
	rGas.Mul(rGas, price)

227
	self.balance.Sub(self.balance, rGas)
228 229 230
}

func (self *StateObject) Copy() *StateObject {
231
	stateObject := NewStateObject(self.Address(), self.db)
232
	stateObject.balance.Set(self.balance)
233
	stateObject.codeHash = ethutil.CopyBytes(self.codeHash)
234
	stateObject.Nonce = self.Nonce
235 236
	if self.State != nil {
		stateObject.State = self.State.Copy()
237 238
	}
	stateObject.Code = ethutil.CopyBytes(self.Code)
239
	stateObject.InitCode = ethutil.CopyBytes(self.InitCode)
240 241
	stateObject.storage = self.storage.Copy()
	stateObject.gasPool.Set(self.gasPool)
obscuren's avatar
obscuren committed
242
	stateObject.remove = self.remove
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265

	return stateObject
}

func (self *StateObject) Set(stateObject *StateObject) {
	*self = *stateObject
}

//
// Attribute accessors
//

func (c *StateObject) N() *big.Int {
	return big.NewInt(int64(c.Nonce))
}

// Returns the address of the contract/account
func (c *StateObject) Address() []byte {
	return c.address
}

// Returns the initialization Code
func (c *StateObject) Init() Code {
266
	return c.InitCode
267 268
}

269
func (self *StateObject) Trie() *trie.Trie {
obscuren's avatar
obscuren committed
270 271 272
	return self.State.trie
}

obscuren's avatar
obscuren committed
273
func (self *StateObject) Root() []byte {
obscuren's avatar
obscuren committed
274
	return self.Trie().Root()
obscuren's avatar
obscuren committed
275 276
}

277 278 279 280
func (self *StateObject) SetCode(code []byte) {
	self.Code = code
}

281 282 283 284 285 286
//
// Encoding
//

// State object encoding methods
func (c *StateObject) RlpEncode() []byte {
obscuren's avatar
obscuren committed
287
	return ethutil.Encode([]interface{}{c.Nonce, c.balance, c.Root(), c.CodeHash()})
288 289 290
}

func (c *StateObject) CodeHash() ethutil.Bytes {
291
	return crypto.Sha3(c.Code)
292 293 294 295 296
}

func (c *StateObject) RlpDecode(data []byte) {
	decoder := ethutil.NewValueFromBytes(data)
	c.Nonce = decoder.Get(0).Uint()
297
	c.balance = decoder.Get(1).BigInt()
298
	c.State = New(decoder.Get(2).Bytes(), c.db) //New(trie.New(ethutil.Config.Db, decoder.Get(2).Interface()))
299 300 301
	c.storage = make(map[string]*ethutil.Value)
	c.gasPool = new(big.Int)

302
	c.codeHash = decoder.Get(3).Bytes()
303

304
	c.Code, _ = c.db.Get(c.codeHash)
305 306 307 308 309 310 311 312 313
}

// Storage change object. Used by the manifest for notifying changes to
// the sub channels.
type StorageState struct {
	StateAddress []byte
	Address      []byte
	Value        *big.Int
}