state_object.go 10.7 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
	"math/big"
24
	"time"
25

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

32
var emptyCodeHash = crypto.Keccak256(nil)
33

34 35
type Code []byte

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

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

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

	return
}

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

	return cpy
}

59
// stateObject represents an Ethereum account which is being modified.
60 61 62 63 64
//
// 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.
65
type stateObject struct {
66 67 68 69
	address  common.Address
	addrHash common.Hash // hash of ethereum address of the account
	data     Account
	db       *StateDB
70 71 72 73 74 75 76 77 78

	// 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.
79 80
	trie Trie // storage trie, which becomes non-nil on first access
	code Code // contract bytecode, which gets set when code is loaded
81

82
	originStorage Storage // Storage cache of original entries to dedup rewrites
83
	dirtyStorage  Storage // Storage entries that need to be flushed to disk
84

85
	// Cache flags.
86 87
	// When an object is marked suicided it will be delete from the trie
	// during the "update" phase of the state transition.
88
	dirtyCode bool // true if the code was updated
89
	suicided  bool
90
	deleted   bool
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) *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 116 117 118 119
	return &stateObject{
		db:            db,
		address:       address,
		addrHash:      crypto.Keccak256Hash(address[:]),
		data:          data,
120
		originStorage: make(Storage),
121 122
		dirtyStorage:  make(Storage),
	}
123 124
}

125
// EncodeRLP implements rlp.Encoder.
126 127
func (s *stateObject) EncodeRLP(w io.Writer) error {
	return rlp.Encode(w, s.data)
128 129
}

130
// setError remembers the first non-nil error it is called with.
131 132 133
func (s *stateObject) setError(err error) {
	if s.dbErr == nil {
		s.dbErr = err
134
	}
135 136
}

137 138
func (s *stateObject) markSuicided() {
	s.suicided = true
139 140
}

141 142 143
func (s *stateObject) touch() {
	s.db.journal.append(touchChange{
		account: &s.address,
144
	})
145
	if s.address == ripemd {
146 147
		// Explicitly put it in the dirty-cache, which is otherwise generated from
		// flattened journals.
148
		s.db.journal.dirty(s.address)
149 150 151
	}
}

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

164
// GetState retrieves a value from the account storage trie.
165
func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
166
	// If we have a dirty value for this state entry, return it
167
	value, dirty := s.dirtyStorage[key]
168 169 170 171
	if dirty {
		return value
	}
	// Otherwise return the entry's original value
172
	return s.GetCommittedState(db, key)
173 174 175
}

// GetCommittedState retrieves a value from the committed account storage trie.
176
func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
177
	// If we have the original value cached, return that
178
	value, cached := s.originStorage[key]
179
	if cached {
180 181
		return value
	}
182 183
	// Track the amount of time wasted on reading the storge trie
	if metrics.EnabledExpensive {
184
		defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now())
185
	}
186
	// Otherwise load the value from the database
187
	enc, err := s.getTrie(db).TryGet(key[:])
188
	if err != nil {
189
		s.setError(err)
190 191 192
		return common.Hash{}
	}
	if len(enc) > 0 {
193 194
		_, content, _, err := rlp.Split(enc)
		if err != nil {
195
			s.setError(err)
196 197 198
		}
		value.SetBytes(content)
	}
199
	s.originStorage[key] = value
200 201 202
	return value
}

203
// SetState updates a value in account storage.
204
func (s *stateObject) SetState(db Database, key, value common.Hash) {
205
	// If the new value is the same as old, don't set
206
	prev := s.GetState(db, key)
207 208 209 210
	if prev == value {
		return
	}
	// New value is different, update and journal the change
211 212
	s.db.journal.append(storageChange{
		account:  &s.address,
213
		key:      key,
214
		prevalue: prev,
215
	})
216
	s.setState(key, value)
217 218
}

219 220
func (s *stateObject) setState(key, value common.Hash) {
	s.dirtyStorage[key] = value
221 222
}

223
// updateTrie writes cached storage modifications into the object's storage trie.
224
func (s *stateObject) updateTrie(db Database) Trie {
225 226
	// Track the amount of time wasted on updating the storge trie
	if metrics.EnabledExpensive {
227
		defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
228 229
	}
	// Update all the dirty slots in the trie
230 231 232
	tr := s.getTrie(db)
	for key, value := range s.dirtyStorage {
		delete(s.dirtyStorage, key)
233 234

		// Skip noop changes, persist actual changes
235
		if value == s.originStorage[key] {
236 237
			continue
		}
238
		s.originStorage[key] = value
239

240
		if (value == common.Hash{}) {
241
			s.setError(tr.TryDelete(key[:]))
242 243
			continue
		}
244 245
		// Encoding []byte cannot fail, ok to ignore the error.
		v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00"))
246
		s.setError(tr.TryUpdate(key[:], v))
247
	}
248
	return tr
249 250
}

251
// UpdateRoot sets the trie root to the current root hash of
252 253
func (s *stateObject) updateRoot(db Database) {
	s.updateTrie(db)
254 255 256

	// Track the amount of time wasted on hashing the storge trie
	if metrics.EnabledExpensive {
257
		defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
258
	}
259
	s.data.Root = s.trie.Hash()
260 261
}

hadv's avatar
hadv committed
262
// CommitTrie the storage trie of the object to db.
263
// This updates the trie root.
264 265 266 267
func (s *stateObject) CommitTrie(db Database) error {
	s.updateTrie(db)
	if s.dbErr != nil {
		return s.dbErr
268
	}
269 270
	// Track the amount of time wasted on committing the storge trie
	if metrics.EnabledExpensive {
271
		defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
272
	}
273
	root, err := s.trie.Commit(nil)
274
	if err == nil {
275
		s.data.Root = root
276 277 278 279
	}
	return err
}

280 281
// AddBalance removes amount from c's balance.
// It is used to add funds to the destination account of a transfer.
282
func (s *stateObject) AddBalance(amount *big.Int) {
283 284
	// EIP158: We must check emptiness for the objects such that the account
	// clearing (0,0,0 objects) can take effect.
285
	if amount.Sign() == 0 {
286 287
		if s.empty() {
			s.touch()
288 289
		}

290 291
		return
	}
292
	s.SetBalance(new(big.Int).Add(s.Balance(), amount))
293 294
}

295 296
// SubBalance removes amount from c's balance.
// It is used to remove funds from the origin account of a transfer.
297
func (s *stateObject) SubBalance(amount *big.Int) {
298
	if amount.Sign() == 0 {
299 300
		return
	}
301
	s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
302 303
}

304 305 306 307
func (s *stateObject) SetBalance(amount *big.Int) {
	s.db.journal.append(balanceChange{
		account: &s.address,
		prev:    new(big.Int).Set(s.data.Balance),
308
	})
309
	s.setBalance(amount)
310 311
}

312 313
func (s *stateObject) setBalance(amount *big.Int) {
	s.data.Balance = amount
314 315
}

316
// Return the gas back to the origin. Used by the Virtual machine or Closures
317
func (s *stateObject) ReturnGas(gas *big.Int) {}
318

319 320 321 322
func (s *stateObject) deepCopy(db *StateDB) *stateObject {
	stateObject := newObject(db, s.address, s.data)
	if s.trie != nil {
		stateObject.trie = db.db.CopyTrie(s.trie)
323
	}
324 325 326 327 328 329
	stateObject.code = s.code
	stateObject.dirtyStorage = s.dirtyStorage.Copy()
	stateObject.originStorage = s.originStorage.Copy()
	stateObject.suicided = s.suicided
	stateObject.dirtyCode = s.dirtyCode
	stateObject.deleted = s.deleted
330 331 332 333 334 335 336 337
	return stateObject
}

//
// Attribute accessors
//

// Returns the address of the contract/account
338 339
func (s *stateObject) Address() common.Address {
	return s.address
340 341
}

342
// Code returns the contract code associated with this object, if any.
343 344 345
func (s *stateObject) Code(db Database) []byte {
	if s.code != nil {
		return s.code
346
	}
347
	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
348 349
		return nil
	}
350
	code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
351
	if err != nil {
352
		s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
353
	}
354
	s.code = code
355
	return code
obscuren's avatar
obscuren committed
356 357
}

358 359 360 361 362
func (s *stateObject) SetCode(codeHash common.Hash, code []byte) {
	prevcode := s.Code(s.db.db)
	s.db.journal.append(codeChange{
		account:  &s.address,
		prevhash: s.CodeHash(),
363 364
		prevcode: prevcode,
	})
365
	s.setCode(codeHash, code)
366 367
}

368 369 370 371
func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
	s.code = code
	s.data.CodeHash = codeHash[:]
	s.dirtyCode = true
372 373
}

374 375 376 377
func (s *stateObject) SetNonce(nonce uint64) {
	s.db.journal.append(nonceChange{
		account: &s.address,
		prev:    s.data.Nonce,
378
	})
379
	s.setNonce(nonce)
380 381
}

382 383
func (s *stateObject) setNonce(nonce uint64) {
	s.data.Nonce = nonce
384 385
}

386 387
func (s *stateObject) CodeHash() []byte {
	return s.data.CodeHash
388 389
}

390 391
func (s *stateObject) Balance() *big.Int {
	return s.data.Balance
392 393
}

394 395
func (s *stateObject) Nonce() uint64 {
	return s.data.Nonce
396 397
}

398
// Never called, but must be present to allow stateObject to be used
399 400
// as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome.
401
func (s *stateObject) Value() *big.Int {
402
	panic("Value on stateObject should never be called")
403
}