github.com/ccm-chain/ccmchain@v1.0.0/core/state/state_object.go (about) 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 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 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 // GNU Lesser General Public License for more details. 13 // 14 // 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 17 package state 18 19 import ( 20 "bytes" 21 "fmt" 22 "io" 23 "math/big" 24 "time" 25 26 "github.com/ccm-chain/ccmchain/common" 27 "github.com/ccm-chain/ccmchain/crypto" 28 "github.com/ccm-chain/ccmchain/metrics" 29 "github.com/ccm-chain/ccmchain/rlp" 30 ) 31 32 var emptyCodeHash = crypto.Keccak256(nil) 33 34 type Code []byte 35 36 func (c Code) String() string { 37 return string(c) //strings.Join(Disassemble(c), " ") 38 } 39 40 type Storage map[common.Hash]common.Hash 41 42 func (s Storage) String() (str string) { 43 for key, value := range s { 44 str += fmt.Sprintf("%X : %X\n", key, value) 45 } 46 47 return 48 } 49 50 func (s Storage) Copy() Storage { 51 cpy := make(Storage) 52 for key, value := range s { 53 cpy[key] = value 54 } 55 56 return cpy 57 } 58 59 // stateObject represents an Ethereum account which is being modified. 60 // 61 // The usage pattern is as follows: 62 // First you need to obtain a state object. 63 // Account values can be accessed and modified through the object. 64 // Finally, call CommitTrie to write the modified storage trie into a database. 65 type stateObject struct { 66 address common.Address 67 addrHash common.Hash // hash of ethereum address of the account 68 data Account 69 db *StateDB 70 71 // DB error. 72 // State objects are used by the consensus core and VM which are 73 // unable to deal with database-level errors. Any error that occurs 74 // during a database read is memoized here and will eventually be returned 75 // by StateDB.Commit. 76 dbErr error 77 78 // Write caches. 79 trie Trie // storage trie, which becomes non-nil on first access 80 code Code // contract bytecode, which gets set when code is loaded 81 82 originStorage Storage // Storage cache of original entries to dedup rewrites, reset for every transaction 83 pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block 84 dirtyStorage Storage // Storage entries that have been modified in the current transaction execution 85 fakeStorage Storage // Fake storage which constructed by caller for debugging purpose. 86 87 // Cache flags. 88 // When an object is marked suicided it will be delete from the trie 89 // during the "update" phase of the state transition. 90 dirtyCode bool // true if the code was updated 91 suicided bool 92 deleted bool 93 } 94 95 // empty returns whether the account is considered empty. 96 func (s *stateObject) empty() bool { 97 return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) 98 } 99 100 // Account is the Ethereum consensus representation of accounts. 101 // These objects are stored in the main account trie. 102 type Account struct { 103 Nonce uint64 104 Balance *big.Int 105 Root common.Hash // merkle root of the storage trie 106 CodeHash []byte 107 } 108 109 // newObject creates a state object. 110 func newObject(db *StateDB, address common.Address, data Account) *stateObject { 111 if data.Balance == nil { 112 data.Balance = new(big.Int) 113 } 114 if data.CodeHash == nil { 115 data.CodeHash = emptyCodeHash 116 } 117 if data.Root == (common.Hash{}) { 118 data.Root = emptyRoot 119 } 120 return &stateObject{ 121 db: db, 122 address: address, 123 addrHash: crypto.Keccak256Hash(address[:]), 124 data: data, 125 originStorage: make(Storage), 126 pendingStorage: make(Storage), 127 dirtyStorage: make(Storage), 128 } 129 } 130 131 // EncodeRLP implements rlp.Encoder. 132 func (s *stateObject) EncodeRLP(w io.Writer) error { 133 return rlp.Encode(w, s.data) 134 } 135 136 // setError remembers the first non-nil error it is called with. 137 func (s *stateObject) setError(err error) { 138 if s.dbErr == nil { 139 s.dbErr = err 140 } 141 } 142 143 func (s *stateObject) markSuicided() { 144 s.suicided = true 145 } 146 147 func (s *stateObject) touch() { 148 s.db.journal.append(touchChange{ 149 account: &s.address, 150 }) 151 if s.address == ripemd { 152 // Explicitly put it in the dirty-cache, which is otherwise generated from 153 // flattened journals. 154 s.db.journal.dirty(s.address) 155 } 156 } 157 158 func (s *stateObject) getTrie(db Database) Trie { 159 if s.trie == nil { 160 var err error 161 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 162 if err != nil { 163 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 164 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 165 } 166 } 167 return s.trie 168 } 169 170 // GetState retrieves a value from the account storage trie. 171 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 172 // If the fake storage is set, only lookup the state here(in the debugging mode) 173 if s.fakeStorage != nil { 174 return s.fakeStorage[key] 175 } 176 // If we have a dirty value for this state entry, return it 177 value, dirty := s.dirtyStorage[key] 178 if dirty { 179 return value 180 } 181 // Otherwise return the entry's original value 182 return s.GetCommittedState(db, key) 183 } 184 185 // GetCommittedState retrieves a value from the committed account storage trie. 186 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 187 // If the fake storage is set, only lookup the state here(in the debugging mode) 188 if s.fakeStorage != nil { 189 return s.fakeStorage[key] 190 } 191 // If we have a pending write or clean cached, return that 192 if value, pending := s.pendingStorage[key]; pending { 193 return value 194 } 195 if value, cached := s.originStorage[key]; cached { 196 return value 197 } 198 // If no live objects are available, attempt to use snapshots 199 var ( 200 enc []byte 201 err error 202 ) 203 if s.db.snap != nil { 204 if metrics.EnabledExpensive { 205 defer func(start time.Time) { s.db.SnapshotStorageReads += time.Since(start) }(time.Now()) 206 } 207 // If the object was destructed in *this* block (and potentially resurrected), 208 // the storage has been cleared out, and we should *not* consult the previous 209 // snapshot about any storage values. The only possible alternatives are: 210 // 1) resurrect happened, and new slot values were set -- those should 211 // have been handles via pendingStorage above. 212 // 2) we don't have new values, and can deliver empty response back 213 if _, destructed := s.db.snapDestructs[s.addrHash]; destructed { 214 return common.Hash{} 215 } 216 enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes())) 217 } 218 // If snapshot unavailable or reading from it failed, load from the database 219 if s.db.snap == nil || err != nil { 220 if metrics.EnabledExpensive { 221 defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now()) 222 } 223 if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil { 224 s.setError(err) 225 return common.Hash{} 226 } 227 } 228 var value common.Hash 229 if len(enc) > 0 { 230 _, content, _, err := rlp.Split(enc) 231 if err != nil { 232 s.setError(err) 233 } 234 value.SetBytes(content) 235 } 236 s.originStorage[key] = value 237 return value 238 } 239 240 // SetState updates a value in account storage. 241 func (s *stateObject) SetState(db Database, key, value common.Hash) { 242 // If the fake storage is set, put the temporary state update here. 243 if s.fakeStorage != nil { 244 s.fakeStorage[key] = value 245 return 246 } 247 // If the new value is the same as old, don't set 248 prev := s.GetState(db, key) 249 if prev == value { 250 return 251 } 252 // New value is different, update and journal the change 253 s.db.journal.append(storageChange{ 254 account: &s.address, 255 key: key, 256 prevalue: prev, 257 }) 258 s.setState(key, value) 259 } 260 261 // SetStorage replaces the entire state storage with the given one. 262 // 263 // After this function is called, all original state will be ignored and state 264 // lookup only happens in the fake state storage. 265 // 266 // Note this function should only be used for debugging purpose. 267 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 268 // Allocate fake storage if it's nil. 269 if s.fakeStorage == nil { 270 s.fakeStorage = make(Storage) 271 } 272 for key, value := range storage { 273 s.fakeStorage[key] = value 274 } 275 // Don't bother journal since this function should only be used for 276 // debugging and the `fake` storage won't be committed to database. 277 } 278 279 func (s *stateObject) setState(key, value common.Hash) { 280 s.dirtyStorage[key] = value 281 } 282 283 // finalise moves all dirty storage slots into the pending area to be hashed or 284 // committed later. It is invoked at the end of every transaction. 285 func (s *stateObject) finalise() { 286 for key, value := range s.dirtyStorage { 287 s.pendingStorage[key] = value 288 } 289 if len(s.dirtyStorage) > 0 { 290 s.dirtyStorage = make(Storage) 291 } 292 } 293 294 // updateTrie writes cached storage modifications into the object's storage trie. 295 // It will return nil if the trie has not been loaded and no changes have been made 296 func (s *stateObject) updateTrie(db Database) Trie { 297 // Make sure all dirty slots are finalized into the pending storage area 298 s.finalise() 299 if len(s.pendingStorage) == 0 { 300 return s.trie 301 } 302 // Track the amount of time wasted on updating the storge trie 303 if metrics.EnabledExpensive { 304 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 305 } 306 // Retrieve the snapshot storage map for the object 307 var storage map[common.Hash][]byte 308 if s.db.snap != nil { 309 // Retrieve the old storage map, if available, create a new one otherwise 310 storage = s.db.snapStorage[s.addrHash] 311 if storage == nil { 312 storage = make(map[common.Hash][]byte) 313 s.db.snapStorage[s.addrHash] = storage 314 } 315 } 316 // Insert all the pending updates into the trie 317 tr := s.getTrie(db) 318 for key, value := range s.pendingStorage { 319 // Skip noop changes, persist actual changes 320 if value == s.originStorage[key] { 321 continue 322 } 323 s.originStorage[key] = value 324 325 var v []byte 326 if (value == common.Hash{}) { 327 s.setError(tr.TryDelete(key[:])) 328 } else { 329 // Encoding []byte cannot fail, ok to ignore the error. 330 v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 331 s.setError(tr.TryUpdate(key[:], v)) 332 } 333 // If state snapshotting is active, cache the data til commit 334 if storage != nil { 335 storage[crypto.Keccak256Hash(key[:])] = v // v will be nil if value is 0x00 336 } 337 } 338 if len(s.pendingStorage) > 0 { 339 s.pendingStorage = make(Storage) 340 } 341 if len(s.pendingStorage) > 0 { 342 s.pendingStorage = make(Storage) 343 } 344 return tr 345 } 346 347 // UpdateRoot sets the trie root to the current root hash of 348 func (s *stateObject) updateRoot(db Database) { 349 // If nothing changed, don't bother with hashing anything 350 if s.updateTrie(db) == nil { 351 return 352 } 353 // Track the amount of time wasted on hashing the storge trie 354 if metrics.EnabledExpensive { 355 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 356 } 357 s.data.Root = s.trie.Hash() 358 } 359 360 // CommitTrie the storage trie of the object to db. 361 // This updates the trie root. 362 func (s *stateObject) CommitTrie(db Database) error { 363 // If nothing changed, don't bother with hashing anything 364 if s.updateTrie(db) == nil { 365 return nil 366 } 367 if s.dbErr != nil { 368 return s.dbErr 369 } 370 // Track the amount of time wasted on committing the storge trie 371 if metrics.EnabledExpensive { 372 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 373 } 374 root, err := s.trie.Commit(nil) 375 if err == nil { 376 s.data.Root = root 377 } 378 return err 379 } 380 381 // AddBalance adds amount to s's balance. 382 // It is used to add funds to the destination account of a transfer. 383 func (s *stateObject) AddBalance(amount *big.Int) { 384 // EIP161: We must check emptiness for the objects such that the account 385 // clearing (0,0,0 objects) can take effect. 386 if amount.Sign() == 0 { 387 if s.empty() { 388 s.touch() 389 } 390 return 391 } 392 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 393 } 394 395 // SubBalance removes amount from s's balance. 396 // It is used to remove funds from the origin account of a transfer. 397 func (s *stateObject) SubBalance(amount *big.Int) { 398 if amount.Sign() == 0 { 399 return 400 } 401 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 402 } 403 404 func (s *stateObject) SetBalance(amount *big.Int) { 405 s.db.journal.append(balanceChange{ 406 account: &s.address, 407 prev: new(big.Int).Set(s.data.Balance), 408 }) 409 s.setBalance(amount) 410 } 411 412 func (s *stateObject) setBalance(amount *big.Int) { 413 s.data.Balance = amount 414 } 415 416 // Return the gas back to the origin. Used by the Virtual machine or Closures 417 func (s *stateObject) ReturnGas(gas *big.Int) {} 418 419 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 420 stateObject := newObject(db, s.address, s.data) 421 if s.trie != nil { 422 stateObject.trie = db.db.CopyTrie(s.trie) 423 } 424 stateObject.code = s.code 425 stateObject.dirtyStorage = s.dirtyStorage.Copy() 426 stateObject.originStorage = s.originStorage.Copy() 427 stateObject.pendingStorage = s.pendingStorage.Copy() 428 stateObject.suicided = s.suicided 429 stateObject.dirtyCode = s.dirtyCode 430 stateObject.deleted = s.deleted 431 return stateObject 432 } 433 434 // 435 // Attribute accessors 436 // 437 438 // Returns the address of the contract/account 439 func (s *stateObject) Address() common.Address { 440 return s.address 441 } 442 443 // Code returns the contract code associated with this object, if any. 444 func (s *stateObject) Code(db Database) []byte { 445 if s.code != nil { 446 return s.code 447 } 448 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 449 return nil 450 } 451 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 452 if err != nil { 453 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 454 } 455 s.code = code 456 return code 457 } 458 459 // CodeSize returns the size of the contract code associated with this object, 460 // or zero if none. This method is an almost mirror of Code, but uses a cache 461 // inside the database to avoid loading codes seen recently. 462 func (s *stateObject) CodeSize(db Database) int { 463 if s.code != nil { 464 return len(s.code) 465 } 466 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 467 return 0 468 } 469 size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash())) 470 if err != nil { 471 s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err)) 472 } 473 return size 474 } 475 476 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 477 prevcode := s.Code(s.db.db) 478 s.db.journal.append(codeChange{ 479 account: &s.address, 480 prevhash: s.CodeHash(), 481 prevcode: prevcode, 482 }) 483 s.setCode(codeHash, code) 484 } 485 486 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 487 s.code = code 488 s.data.CodeHash = codeHash[:] 489 s.dirtyCode = true 490 } 491 492 func (s *stateObject) SetNonce(nonce uint64) { 493 s.db.journal.append(nonceChange{ 494 account: &s.address, 495 prev: s.data.Nonce, 496 }) 497 s.setNonce(nonce) 498 } 499 500 func (s *stateObject) setNonce(nonce uint64) { 501 s.data.Nonce = nonce 502 } 503 504 func (s *stateObject) CodeHash() []byte { 505 return s.data.CodeHash 506 } 507 508 func (s *stateObject) Balance() *big.Int { 509 return s.data.Balance 510 } 511 512 func (s *stateObject) Nonce() uint64 { 513 return s.data.Nonce 514 } 515 516 // Never called, but must be present to allow stateObject to be used 517 // as a vm.Account interface that also satisfies the vm.ContractRef 518 // interface. Interfaces are awesome. 519 func (s *stateObject) Value() *big.Int { 520 panic("Value on stateObject should never be called") 521 }