github.com/isti4github/eth-ecc@v0.0.0-20201227085832-c337f2d99319/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/Onther-Tech/go-ethereum/common" 27 "github.com/Onther-Tech/go-ethereum/crypto" 28 "github.com/Onther-Tech/go-ethereum/metrics" 29 "github.com/Onther-Tech/go-ethereum/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 83 dirtyStorage Storage // Storage entries that need to be flushed to disk 84 fakeStorage Storage // Fake storage which constructed by caller for debugging purpose. 85 86 // Cache flags. 87 // When an object is marked suicided it will be delete from the trie 88 // during the "update" phase of the state transition. 89 dirtyCode bool // true if the code was updated 90 suicided bool 91 deleted bool 92 } 93 94 // empty returns whether the account is considered empty. 95 func (s *stateObject) empty() bool { 96 return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) 97 } 98 99 // Account is the Ethereum consensus representation of accounts. 100 // These objects are stored in the main account trie. 101 type Account struct { 102 Nonce uint64 103 Balance *big.Int 104 Root common.Hash // merkle root of the storage trie 105 CodeHash []byte 106 } 107 108 // newObject creates a state object. 109 func newObject(db *StateDB, address common.Address, data Account) *stateObject { 110 if data.Balance == nil { 111 data.Balance = new(big.Int) 112 } 113 if data.CodeHash == nil { 114 data.CodeHash = emptyCodeHash 115 } 116 return &stateObject{ 117 db: db, 118 address: address, 119 addrHash: crypto.Keccak256Hash(address[:]), 120 data: data, 121 originStorage: make(Storage), 122 dirtyStorage: make(Storage), 123 } 124 } 125 126 // EncodeRLP implements rlp.Encoder. 127 func (s *stateObject) EncodeRLP(w io.Writer) error { 128 return rlp.Encode(w, s.data) 129 } 130 131 // setError remembers the first non-nil error it is called with. 132 func (s *stateObject) setError(err error) { 133 if s.dbErr == nil { 134 s.dbErr = err 135 } 136 } 137 138 func (s *stateObject) markSuicided() { 139 s.suicided = true 140 } 141 142 func (s *stateObject) touch() { 143 s.db.journal.append(touchChange{ 144 account: &s.address, 145 }) 146 if s.address == ripemd { 147 // Explicitly put it in the dirty-cache, which is otherwise generated from 148 // flattened journals. 149 s.db.journal.dirty(s.address) 150 } 151 } 152 153 func (s *stateObject) getTrie(db Database) Trie { 154 if s.trie == nil { 155 var err error 156 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 157 if err != nil { 158 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 159 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 160 } 161 } 162 return s.trie 163 } 164 165 // GetState retrieves a value from the account storage trie. 166 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 167 // If the fake storage is set, only lookup the state here(in the debugging mode) 168 if s.fakeStorage != nil { 169 return s.fakeStorage[key] 170 } 171 // If we have a dirty value for this state entry, return it 172 value, dirty := s.dirtyStorage[key] 173 if dirty { 174 return value 175 } 176 // Otherwise return the entry's original value 177 return s.GetCommittedState(db, key) 178 } 179 180 // GetCommittedState retrieves a value from the committed account storage trie. 181 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 182 // If the fake storage is set, only lookup the state here(in the debugging mode) 183 if s.fakeStorage != nil { 184 return s.fakeStorage[key] 185 } 186 // If we have the original value cached, return that 187 value, cached := s.originStorage[key] 188 if cached { 189 return value 190 } 191 // Track the amount of time wasted on reading the storage trie 192 if metrics.EnabledExpensive { 193 defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now()) 194 } 195 // Otherwise load the value from the database 196 enc, err := s.getTrie(db).TryGet(key[:]) 197 if err != nil { 198 s.setError(err) 199 return common.Hash{} 200 } 201 if len(enc) > 0 { 202 _, content, _, err := rlp.Split(enc) 203 if err != nil { 204 s.setError(err) 205 } 206 value.SetBytes(content) 207 } 208 s.originStorage[key] = value 209 return value 210 } 211 212 // SetState updates a value in account storage. 213 func (s *stateObject) SetState(db Database, key, value common.Hash) { 214 // If the fake storage is set, put the temporary state update here. 215 if s.fakeStorage != nil { 216 s.fakeStorage[key] = value 217 return 218 } 219 // If the new value is the same as old, don't set 220 prev := s.GetState(db, key) 221 if prev == value { 222 return 223 } 224 // New value is different, update and journal the change 225 s.db.journal.append(storageChange{ 226 account: &s.address, 227 key: key, 228 prevalue: prev, 229 }) 230 s.setState(key, value) 231 } 232 233 // SetStorage replaces the entire state storage with the given one. 234 // 235 // After this function is called, all original state will be ignored and state 236 // lookup only happens in the fake state storage. 237 // 238 // Note this function should only be used for debugging purpose. 239 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 240 // Allocate fake storage if it's nil. 241 if s.fakeStorage == nil { 242 s.fakeStorage = make(Storage) 243 } 244 for key, value := range storage { 245 s.fakeStorage[key] = value 246 } 247 // Don't bother journal since this function should only be used for 248 // debugging and the `fake` storage won't be committed to database. 249 } 250 251 func (s *stateObject) setState(key, value common.Hash) { 252 s.dirtyStorage[key] = value 253 } 254 255 // updateTrie writes cached storage modifications into the object's storage trie. 256 func (s *stateObject) updateTrie(db Database) Trie { 257 // Track the amount of time wasted on updating the storge trie 258 if metrics.EnabledExpensive { 259 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 260 } 261 // Update all the dirty slots in the trie 262 tr := s.getTrie(db) 263 for key, value := range s.dirtyStorage { 264 delete(s.dirtyStorage, key) 265 266 // Skip noop changes, persist actual changes 267 if value == s.originStorage[key] { 268 continue 269 } 270 s.originStorage[key] = value 271 272 if (value == common.Hash{}) { 273 s.setError(tr.TryDelete(key[:])) 274 continue 275 } 276 // Encoding []byte cannot fail, ok to ignore the error. 277 v, _ := rlp.EncodeToBytes(bytes.TrimLeft(value[:], "\x00")) 278 s.setError(tr.TryUpdate(key[:], v)) 279 } 280 return tr 281 } 282 283 // UpdateRoot sets the trie root to the current root hash of 284 func (s *stateObject) updateRoot(db Database) { 285 s.updateTrie(db) 286 287 // Track the amount of time wasted on hashing the storge trie 288 if metrics.EnabledExpensive { 289 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 290 } 291 s.data.Root = s.trie.Hash() 292 } 293 294 // CommitTrie the storage trie of the object to db. 295 // This updates the trie root. 296 func (s *stateObject) CommitTrie(db Database) error { 297 s.updateTrie(db) 298 if s.dbErr != nil { 299 return s.dbErr 300 } 301 // Track the amount of time wasted on committing the storge trie 302 if metrics.EnabledExpensive { 303 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 304 } 305 root, err := s.trie.Commit(nil) 306 if err == nil { 307 s.data.Root = root 308 } 309 return err 310 } 311 312 // AddBalance removes amount from c's balance. 313 // It is used to add funds to the destination account of a transfer. 314 func (s *stateObject) AddBalance(amount *big.Int) { 315 // EIP158: We must check emptiness for the objects such that the account 316 // clearing (0,0,0 objects) can take effect. 317 if amount.Sign() == 0 { 318 if s.empty() { 319 s.touch() 320 } 321 322 return 323 } 324 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 325 } 326 327 // SubBalance removes amount from c's balance. 328 // It is used to remove funds from the origin account of a transfer. 329 func (s *stateObject) SubBalance(amount *big.Int) { 330 if amount.Sign() == 0 { 331 return 332 } 333 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 334 } 335 336 func (s *stateObject) SetBalance(amount *big.Int) { 337 s.db.journal.append(balanceChange{ 338 account: &s.address, 339 prev: new(big.Int).Set(s.data.Balance), 340 }) 341 s.setBalance(amount) 342 } 343 344 func (s *stateObject) setBalance(amount *big.Int) { 345 s.data.Balance = amount 346 } 347 348 // Return the gas back to the origin. Used by the Virtual machine or Closures 349 func (s *stateObject) ReturnGas(gas *big.Int) {} 350 351 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 352 stateObject := newObject(db, s.address, s.data) 353 if s.trie != nil { 354 stateObject.trie = db.db.CopyTrie(s.trie) 355 } 356 stateObject.code = s.code 357 stateObject.dirtyStorage = s.dirtyStorage.Copy() 358 stateObject.originStorage = s.originStorage.Copy() 359 stateObject.suicided = s.suicided 360 stateObject.dirtyCode = s.dirtyCode 361 stateObject.deleted = s.deleted 362 return stateObject 363 } 364 365 // 366 // Attribute accessors 367 // 368 369 // Returns the address of the contract/account 370 func (s *stateObject) Address() common.Address { 371 return s.address 372 } 373 374 // Code returns the contract code associated with this object, if any. 375 func (s *stateObject) Code(db Database) []byte { 376 if s.code != nil { 377 return s.code 378 } 379 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 380 return nil 381 } 382 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 383 if err != nil { 384 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 385 } 386 s.code = code 387 return code 388 } 389 390 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 391 prevcode := s.Code(s.db.db) 392 s.db.journal.append(codeChange{ 393 account: &s.address, 394 prevhash: s.CodeHash(), 395 prevcode: prevcode, 396 }) 397 s.setCode(codeHash, code) 398 } 399 400 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 401 s.code = code 402 s.data.CodeHash = codeHash[:] 403 s.dirtyCode = true 404 } 405 406 func (s *stateObject) SetNonce(nonce uint64) { 407 s.db.journal.append(nonceChange{ 408 account: &s.address, 409 prev: s.data.Nonce, 410 }) 411 s.setNonce(nonce) 412 } 413 414 func (s *stateObject) setNonce(nonce uint64) { 415 s.data.Nonce = nonce 416 } 417 418 func (s *stateObject) CodeHash() []byte { 419 return s.data.CodeHash 420 } 421 422 func (s *stateObject) Balance() *big.Int { 423 return s.data.Balance 424 } 425 426 func (s *stateObject) Nonce() uint64 { 427 return s.data.Nonce 428 } 429 430 // Never called, but must be present to allow stateObject to be used 431 // as a vm.Account interface that also satisfies the vm.ContractRef 432 // interface. Interfaces are awesome. 433 func (s *stateObject) Value() *big.Int { 434 panic("Value on stateObject should never be called") 435 }