state_object.go 15.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"
27
	"github.com/ethereum/go-ethereum/core/types"
obscuren's avatar
obscuren committed
28
	"github.com/ethereum/go-ethereum/crypto"
29
	"github.com/ethereum/go-ethereum/metrics"
30
	"github.com/ethereum/go-ethereum/rlp"
31 32
)

33
var emptyCodeHash = crypto.Keccak256(nil)
34

35 36
type Code []byte

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

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

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

	return
}

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

	return cpy
}

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

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

83 84 85 86
	originStorage  Storage // Storage cache of original entries to dedup rewrites, reset for every transaction
	pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block
	dirtyStorage   Storage // Storage entries that have been modified in the current transaction execution
	fakeStorage    Storage // Fake storage which constructed by caller for debugging purpose.
87

88
	// Cache flags.
89 90
	// When an object is marked suicided it will be delete from the trie
	// during the "update" phase of the state transition.
91
	dirtyCode bool // true if the code was updated
92
	suicided  bool
93
	deleted   bool
94 95
}

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

101
// newObject creates a state object.
102
func newObject(db *StateDB, address common.Address, data types.StateAccount) *stateObject {
103 104 105 106 107
	if data.Balance == nil {
		data.Balance = new(big.Int)
	}
	if data.CodeHash == nil {
		data.CodeHash = emptyCodeHash
obscuren's avatar
obscuren committed
108
	}
109 110 111
	if data.Root == (common.Hash{}) {
		data.Root = emptyRoot
	}
112
	return &stateObject{
113 114 115 116 117 118 119
		db:             db,
		address:        address,
		addrHash:       crypto.Keccak256Hash(address[:]),
		data:           data,
		originStorage:  make(Storage),
		pendingStorage: make(Storage),
		dirtyStorage:   make(Storage),
120
	}
121 122
}

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

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

135 136
func (s *stateObject) markSuicided() {
	s.suicided = true
137 138
}

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

150 151
func (s *stateObject) getTrie(db Database) Trie {
	if s.trie == nil {
152 153 154 155 156
		// Try fetching from prefetcher first
		// We don't prefetch empty tries
		if s.data.Root != emptyRoot && s.db.prefetcher != nil {
			// When the miner is creating the pending state, there is no
			// prefetcher
157
			s.trie = s.db.prefetcher.trie(s.data.Root)
158 159 160 161 162 163 164 165
		}
		if s.trie == nil {
			var err error
			s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root)
			if err != nil {
				s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{})
				s.setError(fmt.Errorf("can't create storage trie: %v", err))
			}
166 167
		}
	}
168
	return s.trie
169
}
170

171
// GetState retrieves a value from the account storage trie.
172
func (s *stateObject) GetState(db Database, key common.Hash) common.Hash {
173 174 175 176
	// If the fake storage is set, only lookup the state here(in the debugging mode)
	if s.fakeStorage != nil {
		return s.fakeStorage[key]
	}
177
	// If we have a dirty value for this state entry, return it
178
	value, dirty := s.dirtyStorage[key]
179 180 181 182
	if dirty {
		return value
	}
	// Otherwise return the entry's original value
183
	return s.GetCommittedState(db, key)
184 185 186
}

// GetCommittedState retrieves a value from the committed account storage trie.
187
func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash {
188 189 190 191
	// If the fake storage is set, only lookup the state here(in the debugging mode)
	if s.fakeStorage != nil {
		return s.fakeStorage[key]
	}
192 193 194 195 196
	// If we have a pending write or clean cached, return that
	if value, pending := s.pendingStorage[key]; pending {
		return value
	}
	if value, cached := s.originStorage[key]; cached {
197 198
		return value
	}
199 200
	// If no live objects are available, attempt to use snapshots
	var (
201 202
		enc []byte
		err error
203 204
	)
	if s.db.snap != nil {
205 206 207 208 209 210 211 212 213
		// If the object was destructed in *this* block (and potentially resurrected),
		// the storage has been cleared out, and we should *not* consult the previous
		// snapshot about any storage values. The only possible alternatives are:
		//   1) resurrect happened, and new slot values were set -- those should
		//      have been handles via pendingStorage above.
		//   2) we don't have new values, and can deliver empty response back
		if _, destructed := s.db.snapDestructs[s.addrHash]; destructed {
			return common.Hash{}
		}
214
		start := time.Now()
215
		enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes()))
216 217 218
		if metrics.EnabledExpensive {
			s.db.SnapshotStorageReads += time.Since(start)
		}
219
	}
220
	// If the snapshot is unavailable or reading from it fails, load from the database.
221
	if s.db.snap == nil || err != nil {
222 223
		start := time.Now()
		enc, err = s.getTrie(db).TryGet(key.Bytes())
224
		if metrics.EnabledExpensive {
225
			s.db.StorageReads += time.Since(start)
226
		}
227
		if err != nil {
228 229 230
			s.setError(err)
			return common.Hash{}
		}
231
	}
232
	var value common.Hash
233
	if len(enc) > 0 {
234 235
		_, content, _, err := rlp.Split(enc)
		if err != nil {
236
			s.setError(err)
237 238 239
		}
		value.SetBytes(content)
	}
240
	s.originStorage[key] = value
241 242 243
	return value
}

244
// SetState updates a value in account storage.
245
func (s *stateObject) SetState(db Database, key, value common.Hash) {
246 247 248 249 250
	// If the fake storage is set, put the temporary state update here.
	if s.fakeStorage != nil {
		s.fakeStorage[key] = value
		return
	}
251
	// If the new value is the same as old, don't set
252
	prev := s.GetState(db, key)
253 254 255 256
	if prev == value {
		return
	}
	// New value is different, update and journal the change
257 258
	s.db.journal.append(storageChange{
		account:  &s.address,
259
		key:      key,
260
		prevalue: prev,
261
	})
262
	s.setState(key, value)
263 264
}

265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
// SetStorage replaces the entire state storage with the given one.
//
// After this function is called, all original state will be ignored and state
// lookup only happens in the fake state storage.
//
// Note this function should only be used for debugging purpose.
func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) {
	// Allocate fake storage if it's nil.
	if s.fakeStorage == nil {
		s.fakeStorage = make(Storage)
	}
	for key, value := range storage {
		s.fakeStorage[key] = value
	}
	// Don't bother journal since this function should only be used for
	// debugging and the `fake` storage won't be committed to database.
}

283 284
func (s *stateObject) setState(key, value common.Hash) {
	s.dirtyStorage[key] = value
285 286
}

287 288
// finalise moves all dirty storage slots into the pending area to be hashed or
// committed later. It is invoked at the end of every transaction.
289 290
func (s *stateObject) finalise(prefetch bool) {
	slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage))
291 292
	for key, value := range s.dirtyStorage {
		s.pendingStorage[key] = value
293 294 295
		if value != s.originStorage[key] {
			slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure
		}
296
	}
297 298
	if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot {
		s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch)
299 300 301 302 303 304
	}
	if len(s.dirtyStorage) > 0 {
		s.dirtyStorage = make(Storage)
	}
}

305
// updateTrie writes cached storage modifications into the object's storage trie.
306
// It will return nil if the trie has not been loaded and no changes have been made
307
func (s *stateObject) updateTrie(db Database) Trie {
308
	// Make sure all dirty slots are finalized into the pending storage area
309
	s.finalise(false) // Don't prefetch anymore, pull directly if need be
310 311 312
	if len(s.pendingStorage) == 0 {
		return s.trie
	}
313
	// Track the amount of time wasted on updating the storage trie
314
	if metrics.EnabledExpensive {
315
		defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now())
316
	}
317
	// The snapshot storage map for the object
318
	var storage map[common.Hash][]byte
319
	// Insert all the pending updates into the trie
320
	tr := s.getTrie(db)
321
	hasher := s.db.hasher
322 323

	usedStorage := make([][]byte, 0, len(s.pendingStorage))
324
	for key, value := range s.pendingStorage {
325
		// Skip noop changes, persist actual changes
326
		if value == s.originStorage[key] {
327 328
			continue
		}
329
		s.originStorage[key] = value
330

331
		var v []byte
332
		if (value == common.Hash{}) {
333
			s.setError(tr.TryDelete(key[:]))
334
			s.db.StorageDeleted += 1
335 336 337 338
		} else {
			// Encoding []byte cannot fail, ok to ignore the error.
			v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:]))
			s.setError(tr.TryUpdate(key[:], v))
339
			s.db.StorageUpdated += 1
340 341
		}
		// If state snapshotting is active, cache the data til commit
342 343 344 345 346 347 348 349
		if s.db.snap != nil {
			if storage == nil {
				// Retrieve the old storage map, if available, create a new one otherwise
				if storage = s.db.snapStorage[s.addrHash]; storage == nil {
					storage = make(map[common.Hash][]byte)
					s.db.snapStorage[s.addrHash] = storage
				}
			}
350
			storage[crypto.HashData(hasher, key[:])] = v // v will be nil if it's deleted
351
		}
352 353 354 355
		usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure
	}
	if s.db.prefetcher != nil {
		s.db.prefetcher.used(s.data.Root, usedStorage)
356
	}
357 358 359
	if len(s.pendingStorage) > 0 {
		s.pendingStorage = make(Storage)
	}
360
	return tr
361 362
}

363
// UpdateRoot sets the trie root to the current root hash of
364
func (s *stateObject) updateRoot(db Database) {
365 366 367 368
	// If nothing changed, don't bother with hashing anything
	if s.updateTrie(db) == nil {
		return
	}
369
	// Track the amount of time wasted on hashing the storage trie
370
	if metrics.EnabledExpensive {
371
		defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now())
372
	}
373
	s.data.Root = s.trie.Hash()
374 375
}

hadv's avatar
hadv committed
376
// CommitTrie the storage trie of the object to db.
377
// This updates the trie root.
378
func (s *stateObject) CommitTrie(db Database) (int, error) {
379 380
	// If nothing changed, don't bother with hashing anything
	if s.updateTrie(db) == nil {
381
		return 0, nil
382
	}
383
	if s.dbErr != nil {
384
		return 0, s.dbErr
385
	}
386
	// Track the amount of time wasted on committing the storage trie
387
	if metrics.EnabledExpensive {
388
		defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now())
389
	}
390
	root, committed, err := s.trie.Commit(nil)
391
	if err == nil {
392
		s.data.Root = root
393
	}
394
	return committed, err
395 396
}

397
// AddBalance adds amount to s's balance.
398
// It is used to add funds to the destination account of a transfer.
399
func (s *stateObject) AddBalance(amount *big.Int) {
400
	// EIP161: We must check emptiness for the objects such that the account
401
	// clearing (0,0,0 objects) can take effect.
402
	if amount.Sign() == 0 {
403 404
		if s.empty() {
			s.touch()
405
		}
406 407
		return
	}
408
	s.SetBalance(new(big.Int).Add(s.Balance(), amount))
409 410
}

411
// SubBalance removes amount from s's balance.
412
// It is used to remove funds from the origin account of a transfer.
413
func (s *stateObject) SubBalance(amount *big.Int) {
414
	if amount.Sign() == 0 {
415 416
		return
	}
417
	s.SetBalance(new(big.Int).Sub(s.Balance(), amount))
418 419
}

420 421 422 423
func (s *stateObject) SetBalance(amount *big.Int) {
	s.db.journal.append(balanceChange{
		account: &s.address,
		prev:    new(big.Int).Set(s.data.Balance),
424
	})
425
	s.setBalance(amount)
426 427
}

428 429
func (s *stateObject) setBalance(amount *big.Int) {
	s.data.Balance = amount
430 431
}

432 433 434 435
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)
436
	}
437 438 439
	stateObject.code = s.code
	stateObject.dirtyStorage = s.dirtyStorage.Copy()
	stateObject.originStorage = s.originStorage.Copy()
440
	stateObject.pendingStorage = s.pendingStorage.Copy()
441 442 443
	stateObject.suicided = s.suicided
	stateObject.dirtyCode = s.dirtyCode
	stateObject.deleted = s.deleted
444 445 446 447 448 449 450 451
	return stateObject
}

//
// Attribute accessors
//

// Returns the address of the contract/account
452 453
func (s *stateObject) Address() common.Address {
	return s.address
454 455
}

456
// Code returns the contract code associated with this object, if any.
457 458 459
func (s *stateObject) Code(db Database) []byte {
	if s.code != nil {
		return s.code
460
	}
461
	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
462 463
		return nil
	}
464
	code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash()))
465
	if err != nil {
466
		s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err))
467
	}
468
	s.code = code
469
	return code
obscuren's avatar
obscuren committed
470 471
}

472
// CodeSize returns the size of the contract code associated with this object,
473
// or zero if none. This method is an almost mirror of Code, but uses a cache
474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
// inside the database to avoid loading codes seen recently.
func (s *stateObject) CodeSize(db Database) int {
	if s.code != nil {
		return len(s.code)
	}
	if bytes.Equal(s.CodeHash(), emptyCodeHash) {
		return 0
	}
	size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash()))
	if err != nil {
		s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err))
	}
	return size
}

489 490 491 492 493
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(),
494 495
		prevcode: prevcode,
	})
496
	s.setCode(codeHash, code)
497 498
}

499 500 501 502
func (s *stateObject) setCode(codeHash common.Hash, code []byte) {
	s.code = code
	s.data.CodeHash = codeHash[:]
	s.dirtyCode = true
503 504
}

505 506 507 508
func (s *stateObject) SetNonce(nonce uint64) {
	s.db.journal.append(nonceChange{
		account: &s.address,
		prev:    s.data.Nonce,
509
	})
510
	s.setNonce(nonce)
511 512
}

513 514
func (s *stateObject) setNonce(nonce uint64) {
	s.data.Nonce = nonce
515 516
}

517 518
func (s *stateObject) CodeHash() []byte {
	return s.data.CodeHash
519 520
}

521 522
func (s *stateObject) Balance() *big.Int {
	return s.data.Balance
523 524
}

525 526
func (s *stateObject) Nonce() uint64 {
	return s.data.Nonce
527 528
}

529
// Never called, but must be present to allow stateObject to be used
530 531
// as a vm.Account interface that also satisfies the vm.ContractRef
// interface. Interfaces are awesome.
532
func (s *stateObject) Value() *big.Int {
533
	panic("Value on stateObject should never be called")
534
}