state_object.go 10.1 KB
Newer Older
1
// Copyright 2014 The go-ethereum Authors
2
// This file is part of the go-ethereum library.
3
//
4
// The go-ethereum library is free software: you can redistribute it and/or modify
5 6 7 8
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
9
// The go-ethereum library is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 13 14
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
15
// along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
16

obscuren's avatar
obscuren committed
17
package state
18 19

import (
20
	"bytes"
21
	"fmt"
22
	"io"
23 24
	"math/big"

obscuren's avatar
obscuren committed
25
	"github.com/ethereum/go-ethereum/common"
obscuren's avatar
obscuren committed
26
	"github.com/ethereum/go-ethereum/crypto"
27
	"github.com/ethereum/go-ethereum/rlp"
28
	"github.com/ethereum/go-ethereum/trie"
29 30
)

31
var emptyCodeHash = crypto.Keccak256(nil)
32

33 34 35
type Code []byte

func (self Code) String() string {
36
	return string(self) //strings.Join(Disassemble(self), " ")
37 38
}

39
type Storage map[common.Hash]common.Hash
40

41 42
func (self Storage) String() (str string) {
	for key, value := range self {
43
		str += fmt.Sprintf("%X : %X\n", key, value)
44 45 46 47 48
	}

	return
}

49 50 51 52 53 54 55 56 57
func (self Storage) Copy() Storage {
	cpy := make(Storage)
	for key, value := range self {
		cpy[key] = value
	}

	return cpy
}

58
// stateObject represents an Ethereum account which is being modified.
59 60 61 62 63
//
// The usage pattern is as follows:
// First you need to obtain a state object.
// Account values can be accessed and modified through the object.
// Finally, call CommitTrie to write the modified storage trie into a database.
64
type stateObject struct {
65 66
	address common.Address // Ethereum address of this account
	data    Account
67
	db      *StateDB
68 69 70 71 72 73 74 75 76

	// DB error.
	// State objects are used by the consensus core and VM which are
	// unable to deal with database-level errors. Any error that occurs
	// during a database read is memoized here and will eventually be returned
	// by StateDB.Commit.
	dbErr error

	// Write caches.
77 78 79 80 81
	trie *trie.SecureTrie // storage trie, which becomes non-nil on first access
	code Code             // contract bytecode, which gets set when code is loaded

	cachedStorage Storage // Storage entry cache to avoid duplicate reads
	dirtyStorage  Storage // Storage entries that need to be flushed to disk
82 83

	// Cache flags.
84 85
	// When an object is marked suicided it will be delete from the trie
	// during the "update" phase of the state transition.
86
	dirtyCode bool // true if the code was updated
87
	suicided  bool
88
	touched   bool
89 90
	deleted   bool
	onDirty   func(addr common.Address) // Callback method to mark a state object newly dirty
91 92
}

93
// empty returns whether the account is considered empty.
94
func (s *stateObject) empty() bool {
95
	return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash)
96 97
}

98 99 100 101 102 103 104 105
// Account is the Ethereum consensus representation of accounts.
// These objects are stored in the main account trie.
type Account struct {
	Nonce    uint64
	Balance  *big.Int
	Root     common.Hash // merkle root of the storage trie
	CodeHash []byte
}
obscuren's avatar
obscuren committed
106

107
// newObject creates a state object.
108
func newObject(db *StateDB, address common.Address, data Account, onDirty func(addr common.Address)) *stateObject {
109 110 111 112 113
	if data.Balance == nil {
		data.Balance = new(big.Int)
	}
	if data.CodeHash == nil {
		data.CodeHash = emptyCodeHash
obscuren's avatar
obscuren committed
114
	}
115
	return &stateObject{db: db, address: address, data: data, cachedStorage: make(Storage), dirtyStorage: make(Storage), onDirty: onDirty}
116 117
}

118
// EncodeRLP implements rlp.Encoder.
119
func (c *stateObject) EncodeRLP(w io.Writer) error {
120
	return rlp.Encode(w, c.data)
121 122
}

123
// setError remembers the first non-nil error it is called with.
124
func (self *stateObject) setError(err error) {
125 126
	if self.dbErr == nil {
		self.dbErr = err
127
	}
128 129
}

130
func (self *stateObject) markSuicided() {
131
	self.suicided = true
132 133 134 135
	if self.onDirty != nil {
		self.onDirty(self.Address())
		self.onDirty = nil
	}
136 137
}

138
func (c *stateObject) touch() {
139
	c.db.journal = append(c.db.journal, touchChange{
140 141 142
		account:   &c.address,
		prev:      c.touched,
		prevDirty: c.onDirty == nil,
143 144 145 146 147 148 149 150
	})
	if c.onDirty != nil {
		c.onDirty(c.Address())
		c.onDirty = nil
	}
	c.touched = true
}

151
func (c *stateObject) getTrie(db trie.Database) *trie.SecureTrie {
152 153
	if c.trie == nil {
		var err error
154
		c.trie, err = trie.NewSecure(c.data.Root, db, 0)
155
		if err != nil {
156
			c.trie, _ = trie.NewSecure(common.Hash{}, db, 0)
157
			c.setError(fmt.Errorf("can't create storage trie: %v", err))
158 159
		}
	}
160 161
	return c.trie
}
162

163
// GetState returns a value in account storage.
164
func (self *stateObject) GetState(db trie.Database, key common.Hash) common.Hash {
165
	value, exists := self.cachedStorage[key]
166 167 168 169
	if exists {
		return value
	}
	// Load from DB in case it is missing.
170 171 172 173 174 175 176
	if enc := self.getTrie(db).Get(key[:]); len(enc) > 0 {
		_, content, _, err := rlp.Split(enc)
		if err != nil {
			self.setError(err)
		}
		value.SetBytes(content)
	}
177
	if (value != common.Hash{}) {
178
		self.cachedStorage[key] = value
179
	}
180 181 182
	return value
}

183
// SetState updates a value in account storage.
184
func (self *stateObject) SetState(db trie.Database, key, value common.Hash) {
185 186 187 188 189 190 191 192
	self.db.journal = append(self.db.journal, storageChange{
		account:  &self.address,
		key:      key,
		prevalue: self.GetState(db, key),
	})
	self.setState(key, value)
}

193
func (self *stateObject) setState(key, value common.Hash) {
194 195 196
	self.cachedStorage[key] = value
	self.dirtyStorage[key] = value

197 198 199 200
	if self.onDirty != nil {
		self.onDirty(self.Address())
		self.onDirty = nil
	}
201 202
}

203
// updateTrie writes cached storage modifications into the object's storage trie.
204
func (self *stateObject) updateTrie(db trie.Database) *trie.SecureTrie {
205
	tr := self.getTrie(db)
206 207
	for key, value := range self.dirtyStorage {
		delete(self.dirtyStorage, key)
208
		if (value == common.Hash{}) {
209
			tr.Delete(key[:])
210 211
			continue
		}
212 213 214
		// Encoding []byte cannot fail, ok to ignore the error.
		v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
		tr.Update(key[:], v)
215
	}
216
	return tr
217 218
}

219
// UpdateRoot sets the trie root to the current root hash of
220
func (self *stateObject) updateRoot(db trie.Database) {
221 222 223 224 225 226
	self.updateTrie(db)
	self.data.Root = self.trie.Hash()
}

// CommitTrie the storage trie of the object to dwb.
// This updates the trie root.
227
func (self *stateObject) CommitTrie(db trie.Database, dbw trie.DatabaseWriter) error {
228 229 230 231 232 233 234 235 236 237 238
	self.updateTrie(db)
	if self.dbErr != nil {
		return self.dbErr
	}
	root, err := self.trie.CommitTo(dbw)
	if err == nil {
		self.data.Root = root
	}
	return err
}

239 240
// AddBalance removes amount from c's balance.
// It is used to add funds to the destination account of a transfer.
241
func (c *stateObject) AddBalance(amount *big.Int) {
242 243
	// EIP158: We must check emptiness for the objects such that the account
	// clearing (0,0,0 objects) can take effect.
244
	if amount.Sign() == 0 {
245 246 247 248
		if c.empty() {
			c.touch()
		}

249 250
		return
	}
251
	c.SetBalance(new(big.Int).Add(c.Balance(), amount))
252 253
}

254 255
// SubBalance removes amount from c's balance.
// It is used to remove funds from the origin account of a transfer.
256
func (c *stateObject) SubBalance(amount *big.Int) {
257
	if amount.Sign() == 0 {
258 259
		return
	}
260
	c.SetBalance(new(big.Int).Sub(c.Balance(), amount))
261 262
}

263
func (self *stateObject) SetBalance(amount *big.Int) {
264 265 266 267 268 269 270
	self.db.journal = append(self.db.journal, balanceChange{
		account: &self.address,
		prev:    new(big.Int).Set(self.data.Balance),
	})
	self.setBalance(amount)
}

271
func (self *stateObject) setBalance(amount *big.Int) {
272 273 274 275 276
	self.data.Balance = amount
	if self.onDirty != nil {
		self.onDirty(self.Address())
		self.onDirty = nil
	}
277 278
}

279
// Return the gas back to the origin. Used by the Virtual machine or Closures
280
func (c *stateObject) ReturnGas(gas *big.Int) {}
281

282
func (self *stateObject) deepCopy(db *StateDB, onDirty func(addr common.Address)) *stateObject {
283
	stateObject := newObject(db, self.address, self.data, onDirty)
284 285 286 287 288
	if self.trie != nil {
		// A shallow copy makes the two tries independent.
		cpy := *self.trie
		stateObject.trie = &cpy
	}
289
	stateObject.code = self.code
290 291
	stateObject.dirtyStorage = self.dirtyStorage.Copy()
	stateObject.cachedStorage = self.dirtyStorage.Copy()
292
	stateObject.suicided = self.suicided
293
	stateObject.dirtyCode = self.dirtyCode
294
	stateObject.deleted = self.deleted
295 296 297 298 299 300 301 302
	return stateObject
}

//
// Attribute accessors
//

// Returns the address of the contract/account
303
func (c *stateObject) Address() common.Address {
304 305 306
	return c.address
}

307
// Code returns the contract code associated with this object, if any.
308
func (self *stateObject) Code(db trie.Database) []byte {
309 310 311 312 313 314 315 316 317 318 319 320
	if self.code != nil {
		return self.code
	}
	if bytes.Equal(self.CodeHash(), emptyCodeHash) {
		return nil
	}
	code, err := db.Get(self.CodeHash())
	if err != nil {
		self.setError(fmt.Errorf("can't load code hash %x: %v", self.CodeHash(), err))
	}
	self.code = code
	return code
obscuren's avatar
obscuren committed
321 322
}

323
func (self *stateObject) SetCode(codeHash common.Hash, code []byte) {
324 325 326 327 328 329 330 331 332
	prevcode := self.Code(self.db.db)
	self.db.journal = append(self.db.journal, codeChange{
		account:  &self.address,
		prevhash: self.CodeHash(),
		prevcode: prevcode,
	})
	self.setCode(codeHash, code)
}

333
func (self *stateObject) setCode(codeHash common.Hash, code []byte) {
334
	self.code = code
335
	self.data.CodeHash = codeHash[:]
336 337 338 339 340
	self.dirtyCode = true
	if self.onDirty != nil {
		self.onDirty(self.Address())
		self.onDirty = nil
	}
341 342
}

343
func (self *stateObject) SetNonce(nonce uint64) {
344 345 346 347 348 349 350
	self.db.journal = append(self.db.journal, nonceChange{
		account: &self.address,
		prev:    self.data.Nonce,
	})
	self.setNonce(nonce)
}

351
func (self *stateObject) setNonce(nonce uint64) {
352 353 354 355 356 357 358
	self.data.Nonce = nonce
	if self.onDirty != nil {
		self.onDirty(self.Address())
		self.onDirty = nil
	}
}

359
func (self *stateObject) CodeHash() []byte {
360 361 362
	return self.data.CodeHash
}

363
func (self *stateObject) Balance() *big.Int {
364
	return self.data.Balance
365 366
}

367
func (self *stateObject) Nonce() uint64 {
368
	return self.data.Nonce
369 370
}

371
// Never called, but must be present to allow stateObject to be used
372 373
// as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome.
374 375
func (self *stateObject) Value() *big.Int {
	panic("Value on stateObject should never be called")
376
}