gitee.com/liu-zhao234568/cntest@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 "gitee.com/liu-zhao234568/cntest/common" 27 "gitee.com/liu-zhao234568/cntest/crypto" 28 "gitee.com/liu-zhao234568/cntest/metrics" 29 "gitee.com/liu-zhao234568/cntest/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 // Try fetching from prefetcher first 161 // We don't prefetch empty tries 162 if s.data.Root != emptyRoot && s.db.prefetcher != nil { 163 // When the miner is creating the pending state, there is no 164 // prefetcher 165 s.trie = s.db.prefetcher.trie(s.data.Root) 166 } 167 if s.trie == nil { 168 var err error 169 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 170 if err != nil { 171 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 172 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 173 } 174 } 175 } 176 return s.trie 177 } 178 179 // GetState retrieves a value from the account storage trie. 180 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 181 // If the fake storage is set, only lookup the state here(in the debugging mode) 182 if s.fakeStorage != nil { 183 return s.fakeStorage[key] 184 } 185 // If we have a dirty value for this state entry, return it 186 value, dirty := s.dirtyStorage[key] 187 if dirty { 188 return value 189 } 190 // Otherwise return the entry's original value 191 return s.GetCommittedState(db, key) 192 } 193 194 // GetCommittedState retrieves a value from the committed account storage trie. 195 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 196 // If the fake storage is set, only lookup the state here(in the debugging mode) 197 if s.fakeStorage != nil { 198 return s.fakeStorage[key] 199 } 200 // If we have a pending write or clean cached, return that 201 if value, pending := s.pendingStorage[key]; pending { 202 return value 203 } 204 if value, cached := s.originStorage[key]; cached { 205 return value 206 } 207 // If no live objects are available, attempt to use snapshots 208 var ( 209 enc []byte 210 err error 211 meter *time.Duration 212 ) 213 readStart := time.Now() 214 if metrics.EnabledExpensive { 215 // If the snap is 'under construction', the first lookup may fail. If that 216 // happens, we don't want to double-count the time elapsed. Thus this 217 // dance with the metering. 218 defer func() { 219 if meter != nil { 220 *meter += time.Since(readStart) 221 } 222 }() 223 } 224 if s.db.snap != nil { 225 if metrics.EnabledExpensive { 226 meter = &s.db.SnapshotStorageReads 227 } 228 // If the object was destructed in *this* block (and potentially resurrected), 229 // the storage has been cleared out, and we should *not* consult the previous 230 // snapshot about any storage values. The only possible alternatives are: 231 // 1) resurrect happened, and new slot values were set -- those should 232 // have been handles via pendingStorage above. 233 // 2) we don't have new values, and can deliver empty response back 234 if _, destructed := s.db.snapDestructs[s.addrHash]; destructed { 235 return common.Hash{} 236 } 237 enc, err = s.db.snap.Storage(s.addrHash, crypto.Keccak256Hash(key.Bytes())) 238 } 239 // If snapshot unavailable or reading from it failed, load from the database 240 if s.db.snap == nil || err != nil { 241 if meter != nil { 242 // If we already spent time checking the snapshot, account for it 243 // and reset the readStart 244 *meter += time.Since(readStart) 245 readStart = time.Now() 246 } 247 if metrics.EnabledExpensive { 248 meter = &s.db.StorageReads 249 } 250 if enc, err = s.getTrie(db).TryGet(key.Bytes()); err != nil { 251 s.setError(err) 252 return common.Hash{} 253 } 254 } 255 var value common.Hash 256 if len(enc) > 0 { 257 _, content, _, err := rlp.Split(enc) 258 if err != nil { 259 s.setError(err) 260 } 261 value.SetBytes(content) 262 } 263 s.originStorage[key] = value 264 return value 265 } 266 267 // SetState updates a value in account storage. 268 func (s *stateObject) SetState(db Database, key, value common.Hash) { 269 // If the fake storage is set, put the temporary state update here. 270 if s.fakeStorage != nil { 271 s.fakeStorage[key] = value 272 return 273 } 274 // If the new value is the same as old, don't set 275 prev := s.GetState(db, key) 276 if prev == value { 277 return 278 } 279 // New value is different, update and journal the change 280 s.db.journal.append(storageChange{ 281 account: &s.address, 282 key: key, 283 prevalue: prev, 284 }) 285 s.setState(key, value) 286 } 287 288 // SetStorage replaces the entire state storage with the given one. 289 // 290 // After this function is called, all original state will be ignored and state 291 // lookup only happens in the fake state storage. 292 // 293 // Note this function should only be used for debugging purpose. 294 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 295 // Allocate fake storage if it's nil. 296 if s.fakeStorage == nil { 297 s.fakeStorage = make(Storage) 298 } 299 for key, value := range storage { 300 s.fakeStorage[key] = value 301 } 302 // Don't bother journal since this function should only be used for 303 // debugging and the `fake` storage won't be committed to database. 304 } 305 306 func (s *stateObject) setState(key, value common.Hash) { 307 s.dirtyStorage[key] = value 308 } 309 310 // finalise moves all dirty storage slots into the pending area to be hashed or 311 // committed later. It is invoked at the end of every transaction. 312 func (s *stateObject) finalise(prefetch bool) { 313 slotsToPrefetch := make([][]byte, 0, len(s.dirtyStorage)) 314 for key, value := range s.dirtyStorage { 315 s.pendingStorage[key] = value 316 if value != s.originStorage[key] { 317 slotsToPrefetch = append(slotsToPrefetch, common.CopyBytes(key[:])) // Copy needed for closure 318 } 319 } 320 if s.db.prefetcher != nil && prefetch && len(slotsToPrefetch) > 0 && s.data.Root != emptyRoot { 321 s.db.prefetcher.prefetch(s.data.Root, slotsToPrefetch) 322 } 323 if len(s.dirtyStorage) > 0 { 324 s.dirtyStorage = make(Storage) 325 } 326 } 327 328 // updateTrie writes cached storage modifications into the object's storage trie. 329 // It will return nil if the trie has not been loaded and no changes have been made 330 func (s *stateObject) updateTrie(db Database) Trie { 331 // Make sure all dirty slots are finalized into the pending storage area 332 s.finalise(false) // Don't prefetch any more, pull directly if need be 333 if len(s.pendingStorage) == 0 { 334 return s.trie 335 } 336 // Track the amount of time wasted on updating the storage trie 337 if metrics.EnabledExpensive { 338 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 339 } 340 // The snapshot storage map for the object 341 var storage map[common.Hash][]byte 342 // Insert all the pending updates into the trie 343 tr := s.getTrie(db) 344 hasher := s.db.hasher 345 346 usedStorage := make([][]byte, 0, len(s.pendingStorage)) 347 for key, value := range s.pendingStorage { 348 // Skip noop changes, persist actual changes 349 if value == s.originStorage[key] { 350 continue 351 } 352 s.originStorage[key] = value 353 354 var v []byte 355 if (value == common.Hash{}) { 356 s.setError(tr.TryDelete(key[:])) 357 } else { 358 // Encoding []byte cannot fail, ok to ignore the error. 359 v, _ = rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 360 s.setError(tr.TryUpdate(key[:], v)) 361 } 362 // If state snapshotting is active, cache the data til commit 363 if s.db.snap != nil { 364 if storage == nil { 365 // Retrieve the old storage map, if available, create a new one otherwise 366 if storage = s.db.snapStorage[s.addrHash]; storage == nil { 367 storage = make(map[common.Hash][]byte) 368 s.db.snapStorage[s.addrHash] = storage 369 } 370 } 371 storage[crypto.HashData(hasher, key[:])] = v // v will be nil if value is 0x00 372 } 373 usedStorage = append(usedStorage, common.CopyBytes(key[:])) // Copy needed for closure 374 } 375 if s.db.prefetcher != nil { 376 s.db.prefetcher.used(s.data.Root, usedStorage) 377 } 378 if len(s.pendingStorage) > 0 { 379 s.pendingStorage = make(Storage) 380 } 381 return tr 382 } 383 384 // UpdateRoot sets the trie root to the current root hash of 385 func (s *stateObject) updateRoot(db Database) { 386 // If nothing changed, don't bother with hashing anything 387 if s.updateTrie(db) == nil { 388 return 389 } 390 // Track the amount of time wasted on hashing the storage trie 391 if metrics.EnabledExpensive { 392 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 393 } 394 s.data.Root = s.trie.Hash() 395 } 396 397 // CommitTrie the storage trie of the object to db. 398 // This updates the trie root. 399 func (s *stateObject) CommitTrie(db Database) error { 400 // If nothing changed, don't bother with hashing anything 401 if s.updateTrie(db) == nil { 402 return nil 403 } 404 if s.dbErr != nil { 405 return s.dbErr 406 } 407 // Track the amount of time wasted on committing the storage trie 408 if metrics.EnabledExpensive { 409 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 410 } 411 root, err := s.trie.Commit(nil) 412 if err == nil { 413 s.data.Root = root 414 } 415 return err 416 } 417 418 // AddBalance adds amount to s's balance. 419 // It is used to add funds to the destination account of a transfer. 420 func (s *stateObject) AddBalance(amount *big.Int) { 421 // EIP161: We must check emptiness for the objects such that the account 422 // clearing (0,0,0 objects) can take effect. 423 if amount.Sign() == 0 { 424 if s.empty() { 425 s.touch() 426 } 427 return 428 } 429 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 430 } 431 432 // SubBalance removes amount from s's balance. 433 // It is used to remove funds from the origin account of a transfer. 434 func (s *stateObject) SubBalance(amount *big.Int) { 435 if amount.Sign() == 0 { 436 return 437 } 438 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 439 } 440 441 func (s *stateObject) SetBalance(amount *big.Int) { 442 s.db.journal.append(balanceChange{ 443 account: &s.address, 444 prev: new(big.Int).Set(s.data.Balance), 445 }) 446 s.setBalance(amount) 447 } 448 449 func (s *stateObject) setBalance(amount *big.Int) { 450 s.data.Balance = amount 451 } 452 453 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 454 stateObject := newObject(db, s.address, s.data) 455 if s.trie != nil { 456 stateObject.trie = db.db.CopyTrie(s.trie) 457 } 458 stateObject.code = s.code 459 stateObject.dirtyStorage = s.dirtyStorage.Copy() 460 stateObject.originStorage = s.originStorage.Copy() 461 stateObject.pendingStorage = s.pendingStorage.Copy() 462 stateObject.suicided = s.suicided 463 stateObject.dirtyCode = s.dirtyCode 464 stateObject.deleted = s.deleted 465 return stateObject 466 } 467 468 // 469 // Attribute accessors 470 // 471 472 // Returns the address of the contract/account 473 func (s *stateObject) Address() common.Address { 474 return s.address 475 } 476 477 // Code returns the contract code associated with this object, if any. 478 func (s *stateObject) Code(db Database) []byte { 479 if s.code != nil { 480 return s.code 481 } 482 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 483 return nil 484 } 485 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 486 if err != nil { 487 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 488 } 489 s.code = code 490 return code 491 } 492 493 // CodeSize returns the size of the contract code associated with this object, 494 // or zero if none. This method is an almost mirror of Code, but uses a cache 495 // inside the database to avoid loading codes seen recently. 496 func (s *stateObject) CodeSize(db Database) int { 497 if s.code != nil { 498 return len(s.code) 499 } 500 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 501 return 0 502 } 503 size, err := db.ContractCodeSize(s.addrHash, common.BytesToHash(s.CodeHash())) 504 if err != nil { 505 s.setError(fmt.Errorf("can't load code size %x: %v", s.CodeHash(), err)) 506 } 507 return size 508 } 509 510 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 511 prevcode := s.Code(s.db.db) 512 s.db.journal.append(codeChange{ 513 account: &s.address, 514 prevhash: s.CodeHash(), 515 prevcode: prevcode, 516 }) 517 s.setCode(codeHash, code) 518 } 519 520 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 521 s.code = code 522 s.data.CodeHash = codeHash[:] 523 s.dirtyCode = true 524 } 525 526 func (s *stateObject) SetNonce(nonce uint64) { 527 s.db.journal.append(nonceChange{ 528 account: &s.address, 529 prev: s.data.Nonce, 530 }) 531 s.setNonce(nonce) 532 } 533 534 func (s *stateObject) setNonce(nonce uint64) { 535 s.data.Nonce = nonce 536 } 537 538 func (s *stateObject) CodeHash() []byte { 539 return s.data.CodeHash 540 } 541 542 func (s *stateObject) Balance() *big.Int { 543 return s.data.Balance 544 } 545 546 func (s *stateObject) Nonce() uint64 { 547 return s.data.Nonce 548 } 549 550 // Never called, but must be present to allow stateObject to be used 551 // as a vm.Account interface that also satisfies the vm.ContractRef 552 // interface. Interfaces are awesome. 553 func (s *stateObject) Value() *big.Int { 554 panic("Value on stateObject should never be called") 555 }