github.com/Night-mk/quorum@v21.1.0+incompatible/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 "errors" 22 "fmt" 23 "io" 24 "math/big" 25 "sync" 26 "time" 27 28 "github.com/ethereum/go-ethereum/common" 29 "github.com/ethereum/go-ethereum/crypto" 30 "github.com/ethereum/go-ethereum/metrics" 31 "github.com/ethereum/go-ethereum/rlp" 32 ) 33 34 var emptyCodeHash = crypto.Keccak256(nil) 35 36 type Code []byte 37 38 func (c Code) String() string { 39 return string(c) //strings.Join(Disassemble(c), " ") 40 } 41 42 type Storage map[common.Hash]common.Hash 43 44 func (s Storage) String() (str string) { 45 for key, value := range s { 46 str += fmt.Sprintf("%X : %X\n", key, value) 47 } 48 49 return 50 } 51 52 func (s Storage) Copy() Storage { 53 cpy := make(Storage) 54 for key, value := range s { 55 cpy[key] = value 56 } 57 58 return cpy 59 } 60 61 // stateObject represents an Ethereum account which is being modified. 62 // 63 // The usage pattern is as follows: 64 // First you need to obtain a state object. 65 // Account values can be accessed and modified through the object. 66 // Finally, call CommitTrie to write the modified storage trie into a database. 67 type stateObject struct { 68 address common.Address 69 addrHash common.Hash // hash of ethereum address of the account 70 data Account 71 db *StateDB 72 73 // DB error. 74 // State objects are used by the consensus core and VM which are 75 // unable to deal with database-level errors. Any error that occurs 76 // during a database read is memoized here and will eventually be returned 77 // by StateDB.Commit. 78 dbErr error 79 80 // Write caches. 81 trie Trie // storage trie, which becomes non-nil on first access 82 code Code // contract bytecode, which gets set when code is loaded 83 84 // Quorum 85 // contains extra data that is linked to the account 86 accountExtraData *AccountExtraData 87 // as there are many fields in accountExtraData which might be concurrently changed 88 // this is to make sure we can keep track of changes individually. 89 accountExtraDataMutex sync.Mutex 90 91 originStorage Storage // Storage cache of original entries to dedup rewrites, reset for every transaction 92 pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block 93 dirtyStorage Storage // Storage entries that have been modified in the current transaction execution 94 fakeStorage Storage // Fake storage which constructed by caller for debugging purpose. 95 96 // Cache flags. 97 // When an object is marked suicided it will be delete from the trie 98 // during the "update" phase of the state transition. 99 dirtyCode bool // true if the code was updated 100 suicided bool 101 touched bool 102 deleted bool 103 // Quorum 104 // flag to track changes in AccountExtraData 105 dirtyAccountExtraData bool 106 } 107 108 // empty returns whether the account is considered empty. 109 func (s *stateObject) empty() bool { 110 return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) 111 } 112 113 // Account is the Ethereum consensus representation of accounts. 114 // These objects are stored in the main account trie. 115 type Account struct { 116 Nonce uint64 117 Balance *big.Int 118 Root common.Hash // merkle root of the storage trie 119 CodeHash []byte 120 } 121 122 // newObject creates a state object. 123 func newObject(db *StateDB, address common.Address, data Account) *stateObject { 124 if data.Balance == nil { 125 data.Balance = new(big.Int) 126 } 127 if data.CodeHash == nil { 128 data.CodeHash = emptyCodeHash 129 } 130 if data.Root == (common.Hash{}) { 131 data.Root = emptyRoot 132 } 133 return &stateObject{ 134 db: db, 135 address: address, 136 addrHash: crypto.Keccak256Hash(address[:]), 137 data: data, 138 originStorage: make(Storage), 139 pendingStorage: make(Storage), 140 dirtyStorage: make(Storage), 141 } 142 } 143 144 // EncodeRLP implements rlp.Encoder. 145 func (s *stateObject) EncodeRLP(w io.Writer) error { 146 return rlp.Encode(w, s.data) 147 } 148 149 // setError remembers the first non-nil error it is called with. 150 func (s *stateObject) setError(err error) { 151 if s.dbErr == nil { 152 s.dbErr = err 153 } 154 } 155 156 func (s *stateObject) markSuicided() { 157 s.suicided = true 158 } 159 160 func (s *stateObject) touch() { 161 s.db.journal.append(touchChange{ 162 account: &s.address, 163 }) 164 if s.address == ripemd { 165 // Explicitly put it in the dirty-cache, which is otherwise generated from 166 // flattened journals. 167 s.db.journal.dirty(s.address) 168 } 169 s.touched = true 170 } 171 172 func (s *stateObject) getTrie(db Database) Trie { 173 if s.trie == nil { 174 var err error 175 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 176 if err != nil { 177 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 178 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 179 } 180 } 181 return s.trie 182 } 183 184 func (so *stateObject) storageRoot(db Database) common.Hash { 185 return so.getTrie(db).Hash() 186 } 187 188 // GetState retrieves a value from the account storage trie. 189 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 190 // If the fake storage is set, only lookup the state here(in the debugging mode) 191 if s.fakeStorage != nil { 192 return s.fakeStorage[key] 193 } 194 // If we have a dirty value for this state entry, return it 195 value, dirty := s.dirtyStorage[key] 196 if dirty { 197 return value 198 } 199 // Otherwise return the entry's original value 200 return s.GetCommittedState(db, key) 201 } 202 203 // GetCommittedState retrieves a value from the committed account storage trie. 204 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 205 // If the fake storage is set, only lookup the state here(in the debugging mode) 206 if s.fakeStorage != nil { 207 return s.fakeStorage[key] 208 } 209 // If we have a pending write or clean cached, return that 210 if value, pending := s.pendingStorage[key]; pending { 211 return value 212 } 213 if value, cached := s.originStorage[key]; cached { 214 return value 215 } 216 // Track the amount of time wasted on reading the storage trie 217 if metrics.EnabledExpensive { 218 defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now()) 219 } 220 // Otherwise load the value from the database 221 enc, err := s.getTrie(db).TryGet(key[:]) 222 if err != nil { 223 s.setError(err) 224 return common.Hash{} 225 } 226 var value common.Hash 227 if len(enc) > 0 { 228 _, content, _, err := rlp.Split(enc) 229 if err != nil { 230 s.setError(err) 231 } 232 value.SetBytes(content) 233 } 234 s.originStorage[key] = value 235 return value 236 } 237 238 // SetState updates a value in account storage. 239 func (s *stateObject) SetState(db Database, key, value common.Hash) { 240 // If the fake storage is set, put the temporary state update here. 241 if s.fakeStorage != nil { 242 s.fakeStorage[key] = value 243 return 244 } 245 // If the new value is the same as old, don't set 246 prev := s.GetState(db, key) 247 if prev == value { 248 return 249 } 250 // New value is different, update and journal the change 251 s.db.journal.append(storageChange{ 252 account: &s.address, 253 key: key, 254 prevalue: prev, 255 }) 256 s.setState(key, value) 257 } 258 259 // SetStorage replaces the entire state storage with the given one. 260 // 261 // After this function is called, all original state will be ignored and state 262 // lookup only happens in the fake state storage. 263 // 264 // Note this function should only be used for debugging purpose. 265 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 266 // Allocate fake storage if it's nil. 267 if s.fakeStorage == nil { 268 s.fakeStorage = make(Storage) 269 } 270 for key, value := range storage { 271 s.fakeStorage[key] = value 272 } 273 // Don't bother journal since this function should only be used for 274 // debugging and the `fake` storage won't be committed to database. 275 } 276 277 func (s *stateObject) setState(key, value common.Hash) { 278 s.dirtyStorage[key] = value 279 } 280 281 // finalise moves all dirty storage slots into the pending area to be hashed or 282 // committed later. It is invoked at the end of every transaction. 283 func (s *stateObject) finalise() { 284 for key, value := range s.dirtyStorage { 285 s.pendingStorage[key] = value 286 } 287 if len(s.dirtyStorage) > 0 { 288 s.dirtyStorage = make(Storage) 289 } 290 } 291 292 // updateTrie writes cached storage modifications into the object's storage trie. 293 func (s *stateObject) updateTrie(db Database) Trie { 294 // Make sure all dirty slots are finalized into the pending storage area 295 s.finalise() 296 297 // Track the amount of time wasted on updating the storge trie 298 if metrics.EnabledExpensive { 299 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 300 } 301 // Insert all the pending updates into the trie 302 tr := s.getTrie(db) 303 for key, value := range s.pendingStorage { 304 // Skip noop changes, persist actual changes 305 if value == s.originStorage[key] { 306 continue 307 } 308 s.originStorage[key] = value 309 310 if (value == common.Hash{}) { 311 s.setError(tr.TryDelete(key[:])) 312 continue 313 } 314 // Encoding []byte cannot fail, ok to ignore the error. 315 v, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 316 s.setError(tr.TryUpdate(key[:], v)) 317 } 318 if len(s.pendingStorage) > 0 { 319 s.pendingStorage = make(Storage) 320 } 321 return tr 322 } 323 324 // UpdateRoot sets the trie root to the current root hash of 325 func (s *stateObject) updateRoot(db Database) { 326 s.updateTrie(db) 327 328 // Track the amount of time wasted on hashing the storge trie 329 if metrics.EnabledExpensive { 330 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 331 } 332 s.data.Root = s.trie.Hash() 333 } 334 335 // CommitTrie the storage trie of the object to db. 336 // This updates the trie root. 337 func (s *stateObject) CommitTrie(db Database) error { 338 s.updateTrie(db) 339 if s.dbErr != nil { 340 return s.dbErr 341 } 342 // Track the amount of time wasted on committing the storge trie 343 if metrics.EnabledExpensive { 344 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 345 } 346 root, err := s.trie.Commit(nil) 347 if err == nil { 348 s.data.Root = root 349 } 350 return err 351 } 352 353 // AddBalance removes amount from c's balance. 354 // It is used to add funds to the destination account of a transfer. 355 func (s *stateObject) AddBalance(amount *big.Int) { 356 // EIP158: We must check emptiness for the objects such that the account 357 // clearing (0,0,0 objects) can take effect. 358 if amount.Sign() == 0 { 359 if s.empty() { 360 s.touch() 361 } 362 363 return 364 } 365 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 366 } 367 368 // SubBalance removes amount from c's balance. 369 // It is used to remove funds from the origin account of a transfer. 370 func (s *stateObject) SubBalance(amount *big.Int) { 371 if amount.Sign() == 0 { 372 return 373 } 374 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 375 } 376 377 func (s *stateObject) SetBalance(amount *big.Int) { 378 s.db.journal.append(balanceChange{ 379 account: &s.address, 380 prev: new(big.Int).Set(s.data.Balance), 381 }) 382 s.setBalance(amount) 383 } 384 385 func (s *stateObject) setBalance(amount *big.Int) { 386 s.data.Balance = amount 387 } 388 389 // Return the gas back to the origin. Used by the Virtual machine or Closures 390 func (s *stateObject) ReturnGas(gas *big.Int) {} 391 392 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 393 stateObject := newObject(db, s.address, s.data) 394 if s.trie != nil { 395 stateObject.trie = db.db.CopyTrie(s.trie) 396 } 397 stateObject.code = s.code 398 stateObject.dirtyStorage = s.dirtyStorage.Copy() 399 stateObject.originStorage = s.originStorage.Copy() 400 stateObject.pendingStorage = s.pendingStorage.Copy() 401 stateObject.suicided = s.suicided 402 stateObject.dirtyCode = s.dirtyCode 403 stateObject.deleted = s.deleted 404 // Quorum - copy AccountExtraData 405 stateObject.accountExtraData = s.accountExtraData 406 stateObject.dirtyAccountExtraData = s.dirtyAccountExtraData 407 408 return stateObject 409 } 410 411 // 412 // Attribute accessors 413 // 414 415 // Returns the address of the contract/account 416 func (s *stateObject) Address() common.Address { 417 return s.address 418 } 419 420 // Code returns the contract code associated with this object, if any. 421 func (s *stateObject) Code(db Database) []byte { 422 if s.code != nil { 423 return s.code 424 } 425 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 426 return nil 427 } 428 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 429 if err != nil { 430 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 431 } 432 s.code = code 433 return code 434 } 435 436 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 437 prevcode := s.Code(s.db.db) 438 s.db.journal.append(codeChange{ 439 account: &s.address, 440 prevhash: s.CodeHash(), 441 prevcode: prevcode, 442 }) 443 s.setCode(codeHash, code) 444 } 445 446 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 447 s.code = code 448 s.data.CodeHash = codeHash[:] 449 s.dirtyCode = true 450 } 451 452 func (s *stateObject) SetNonce(nonce uint64) { 453 s.db.journal.append(nonceChange{ 454 account: &s.address, 455 prev: s.data.Nonce, 456 }) 457 s.setNonce(nonce) 458 } 459 460 func (s *stateObject) setNonce(nonce uint64) { 461 s.data.Nonce = nonce 462 } 463 464 // Quorum 465 // SetAccountExtraData modifies the AccountExtraData reference and journals it 466 func (s *stateObject) SetAccountExtraData(extraData *AccountExtraData) { 467 current, _ := s.AccountExtraData() 468 s.db.journal.append(accountExtraDataChange{ 469 account: &s.address, 470 prev: current, 471 }) 472 s.setAccountExtraData(extraData) 473 } 474 475 // A new AccountExtraData will be created if not exists. 476 // This must be called after successfully acquiring accountExtraDataMutex lock 477 func (s *stateObject) journalAccountExtraData() *AccountExtraData { 478 current, _ := s.AccountExtraData() 479 s.db.journal.append(accountExtraDataChange{ 480 account: &s.address, 481 prev: current.copy(), 482 }) 483 if current == nil { 484 current = &AccountExtraData{} 485 } 486 return current 487 } 488 489 // Quorum 490 // SetStatePrivacyMetadata updates the PrivacyMetadata in AccountExtraData and journals it. 491 func (s *stateObject) SetStatePrivacyMetadata(pm *PrivacyMetadata) { 492 s.accountExtraDataMutex.Lock() 493 defer s.accountExtraDataMutex.Unlock() 494 495 newExtraData := s.journalAccountExtraData() 496 newExtraData.PrivacyMetadata = pm 497 s.setAccountExtraData(newExtraData) 498 } 499 500 // Quorum 501 // SetStatePrivacyMetadata updates the PrivacyMetadata in AccountExtraData and journals it. 502 func (s *stateObject) SetManagedParties(managedParties []string) { 503 s.accountExtraDataMutex.Lock() 504 defer s.accountExtraDataMutex.Unlock() 505 506 newExtraData := s.journalAccountExtraData() 507 newExtraData.ManagedParties = managedParties 508 s.setAccountExtraData(newExtraData) 509 } 510 511 // Quorum 512 // setAccountExtraData modifies the AccountExtraData reference in this state object 513 func (s *stateObject) setAccountExtraData(extraData *AccountExtraData) { 514 s.accountExtraData = extraData 515 s.dirtyAccountExtraData = true 516 } 517 518 func (s *stateObject) CodeHash() []byte { 519 return s.data.CodeHash 520 } 521 522 func (s *stateObject) Balance() *big.Int { 523 return s.data.Balance 524 } 525 526 func (s *stateObject) Nonce() uint64 { 527 return s.data.Nonce 528 } 529 530 // Quorum 531 // AccountExtraData returns the extra data in this state object. 532 // It will also update the reference by searching the accountExtraDataTrie. 533 // 534 // This method enforces on returning error and never returns (nil, nil). 535 func (s *stateObject) AccountExtraData() (*AccountExtraData, error) { 536 if s.accountExtraData != nil { 537 return s.accountExtraData, nil 538 } 539 val, err := s.getCommittedAccountExtraData() 540 if err != nil { 541 return nil, err 542 } 543 s.accountExtraData = val 544 return val, nil 545 } 546 547 // Quorum 548 // getCommittedAccountExtraData looks for an entry in accountExtraDataTrie. 549 // 550 // This method enforces on returning error and never returns (nil, nil). 551 func (s *stateObject) getCommittedAccountExtraData() (*AccountExtraData, error) { 552 val, err := s.db.accountExtraDataTrie.TryGet(s.address.Bytes()) 553 if err != nil { 554 return nil, fmt.Errorf("unable to retrieve data from the accountExtraDataTrie. Cause: %v", err) 555 } 556 if len(val) == 0 { 557 return nil, fmt.Errorf("%s: %w", s.address.Hex(), common.ErrNoAccountExtraData) 558 } 559 var extraData AccountExtraData 560 if err := rlp.DecodeBytes(val, &extraData); err != nil { 561 return nil, fmt.Errorf("unable to decode to AccountExtraData. Cause: %v", err) 562 } 563 return &extraData, nil 564 } 565 566 // Quorum - Privacy Enhancements 567 // PrivacyMetadata returns the reference to PrivacyMetadata. 568 // It will returrn an error if no PrivacyMetadata is in the AccountExtraData. 569 func (s *stateObject) PrivacyMetadata() (*PrivacyMetadata, error) { 570 extraData, err := s.AccountExtraData() 571 if err != nil { 572 return nil, err 573 } 574 // extraData can't be nil. Refer to s.AccountExtraData() 575 if extraData.PrivacyMetadata == nil { 576 return nil, fmt.Errorf("no privacy metadata data for contract %s", s.address.Hex()) 577 } 578 return extraData.PrivacyMetadata, nil 579 } 580 581 func (s *stateObject) GetCommittedPrivacyMetadata() (*PrivacyMetadata, error) { 582 extraData, err := s.getCommittedAccountExtraData() 583 if err != nil { 584 return nil, err 585 } 586 if extraData == nil || extraData.PrivacyMetadata == nil { 587 return nil, fmt.Errorf("The provided contract does not have privacy metadata: %x", s.address) 588 } 589 return extraData.PrivacyMetadata, nil 590 } 591 592 // End Quorum - Privacy Enhancements 593 594 // ManagedParties will return empty if no account extra data found 595 func (s *stateObject) ManagedParties() ([]string, error) { 596 extraData, err := s.AccountExtraData() 597 if errors.Is(err, common.ErrNoAccountExtraData) { 598 return []string{}, nil 599 } 600 if err != nil { 601 return nil, err 602 } 603 // extraData can't be nil. Refer to s.AccountExtraData() 604 return extraData.ManagedParties, nil 605 } 606 607 // Never called, but must be present to allow stateObject to be used 608 // as a vm.Account interface that also satisfies the vm.ContractRef 609 // interface. Interfaces are awesome. 610 func (s *stateObject) Value() *big.Int { 611 panic("Value on stateObject should never be called") 612 }