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