github.com/RobustRoundRobin/quorum@v20.10.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 "fmt" 22 "io" 23 "math/big" 24 "time" 25 26 "github.com/ethereum/go-ethereum/common" 27 "github.com/ethereum/go-ethereum/crypto" 28 "github.com/ethereum/go-ethereum/metrics" 29 "github.com/ethereum/go-ethereum/private/engine" 30 "github.com/ethereum/go-ethereum/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 // Quorum - Privacy Enhancements 84 privacyMetadata *PrivacyMetadata 85 86 originStorage Storage // Storage cache of original entries to dedup rewrites, reset for every transaction 87 pendingStorage Storage // Storage entries that need to be flushed to disk, at the end of an entire block 88 dirtyStorage Storage // Storage entries that have been modified in the current transaction execution 89 fakeStorage Storage // Fake storage which constructed by caller for debugging purpose. 90 91 // Cache flags. 92 // When an object is marked suicided it will be delete from the trie 93 // during the "update" phase of the state transition. 94 dirtyCode bool // true if the code was updated 95 suicided bool 96 touched bool 97 deleted bool 98 // Quroum - Privacy Enhancements 99 dirtyPrivacyMetadata bool 100 } 101 102 // empty returns whether the account is considered empty. 103 func (s *stateObject) empty() bool { 104 return s.data.Nonce == 0 && s.data.Balance.Sign() == 0 && bytes.Equal(s.data.CodeHash, emptyCodeHash) 105 } 106 107 // Account is the Ethereum consensus representation of accounts. 108 // These objects are stored in the main account trie. 109 type Account struct { 110 Nonce uint64 111 Balance *big.Int 112 Root common.Hash // merkle root of the storage trie 113 CodeHash []byte 114 } 115 116 //attached to every private contract account 117 type PrivacyMetadata struct { 118 CreationTxHash common.EncryptedPayloadHash `json:"creationTxHash"` 119 PrivacyFlag engine.PrivacyFlagType `json:"privacyFlag"` 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 func NewStatePrivacyMetadata(creationTxHash common.EncryptedPayloadHash, privacyFlag engine.PrivacyFlagType) *PrivacyMetadata { 145 return &PrivacyMetadata{ 146 CreationTxHash: creationTxHash, 147 PrivacyFlag: privacyFlag, 148 } 149 } 150 151 // EncodeRLP implements rlp.Encoder. 152 func (s *stateObject) EncodeRLP(w io.Writer) error { 153 return rlp.Encode(w, s.data) 154 } 155 156 // setError remembers the first non-nil error it is called with. 157 func (s *stateObject) setError(err error) { 158 if s.dbErr == nil { 159 s.dbErr = err 160 } 161 } 162 163 func (s *stateObject) markSuicided() { 164 s.suicided = true 165 } 166 167 func (s *stateObject) touch() { 168 s.db.journal.append(touchChange{ 169 account: &s.address, 170 }) 171 if s.address == ripemd { 172 // Explicitly put it in the dirty-cache, which is otherwise generated from 173 // flattened journals. 174 s.db.journal.dirty(s.address) 175 } 176 s.touched = true 177 } 178 179 func (s *stateObject) getTrie(db Database) Trie { 180 if s.trie == nil { 181 var err error 182 s.trie, err = db.OpenStorageTrie(s.addrHash, s.data.Root) 183 if err != nil { 184 s.trie, _ = db.OpenStorageTrie(s.addrHash, common.Hash{}) 185 s.setError(fmt.Errorf("can't create storage trie: %v", err)) 186 } 187 } 188 return s.trie 189 } 190 191 func (so *stateObject) storageRoot(db Database) common.Hash { 192 return so.getTrie(db).Hash() 193 } 194 195 // GetState retrieves a value from the account storage trie. 196 func (s *stateObject) GetState(db Database, key common.Hash) common.Hash { 197 // If the fake storage is set, only lookup the state here(in the debugging mode) 198 if s.fakeStorage != nil { 199 return s.fakeStorage[key] 200 } 201 // If we have a dirty value for this state entry, return it 202 value, dirty := s.dirtyStorage[key] 203 if dirty { 204 return value 205 } 206 // Otherwise return the entry's original value 207 return s.GetCommittedState(db, key) 208 } 209 210 // GetCommittedState retrieves a value from the committed account storage trie. 211 func (s *stateObject) GetCommittedState(db Database, key common.Hash) common.Hash { 212 // If the fake storage is set, only lookup the state here(in the debugging mode) 213 if s.fakeStorage != nil { 214 return s.fakeStorage[key] 215 } 216 // If we have a pending write or clean cached, return that 217 if value, pending := s.pendingStorage[key]; pending { 218 return value 219 } 220 if value, cached := s.originStorage[key]; cached { 221 return value 222 } 223 // Track the amount of time wasted on reading the storage trie 224 if metrics.EnabledExpensive { 225 defer func(start time.Time) { s.db.StorageReads += time.Since(start) }(time.Now()) 226 } 227 // Otherwise load the value from the database 228 enc, err := s.getTrie(db).TryGet(key[:]) 229 if err != nil { 230 s.setError(err) 231 return common.Hash{} 232 } 233 var value common.Hash 234 if len(enc) > 0 { 235 _, content, _, err := rlp.Split(enc) 236 if err != nil { 237 s.setError(err) 238 } 239 value.SetBytes(content) 240 } 241 s.originStorage[key] = value 242 return value 243 } 244 245 // SetState updates a value in account storage. 246 func (s *stateObject) SetState(db Database, key, value common.Hash) { 247 // If the fake storage is set, put the temporary state update here. 248 if s.fakeStorage != nil { 249 s.fakeStorage[key] = value 250 return 251 } 252 // If the new value is the same as old, don't set 253 prev := s.GetState(db, key) 254 if prev == value { 255 return 256 } 257 // New value is different, update and journal the change 258 s.db.journal.append(storageChange{ 259 account: &s.address, 260 key: key, 261 prevalue: prev, 262 }) 263 s.setState(key, value) 264 } 265 266 // SetStorage replaces the entire state storage with the given one. 267 // 268 // After this function is called, all original state will be ignored and state 269 // lookup only happens in the fake state storage. 270 // 271 // Note this function should only be used for debugging purpose. 272 func (s *stateObject) SetStorage(storage map[common.Hash]common.Hash) { 273 // Allocate fake storage if it's nil. 274 if s.fakeStorage == nil { 275 s.fakeStorage = make(Storage) 276 } 277 for key, value := range storage { 278 s.fakeStorage[key] = value 279 } 280 // Don't bother journal since this function should only be used for 281 // debugging and the `fake` storage won't be committed to database. 282 } 283 284 func (s *stateObject) setState(key, value common.Hash) { 285 s.dirtyStorage[key] = value 286 } 287 288 // finalise moves all dirty storage slots into the pending area to be hashed or 289 // committed later. It is invoked at the end of every transaction. 290 func (s *stateObject) finalise() { 291 for key, value := range s.dirtyStorage { 292 s.pendingStorage[key] = value 293 } 294 if len(s.dirtyStorage) > 0 { 295 s.dirtyStorage = make(Storage) 296 } 297 } 298 299 // updateTrie writes cached storage modifications into the object's storage trie. 300 func (s *stateObject) updateTrie(db Database) Trie { 301 // Make sure all dirty slots are finalized into the pending storage area 302 s.finalise() 303 304 // Track the amount of time wasted on updating the storge trie 305 if metrics.EnabledExpensive { 306 defer func(start time.Time) { s.db.StorageUpdates += time.Since(start) }(time.Now()) 307 } 308 // Insert all the pending updates into the trie 309 tr := s.getTrie(db) 310 for key, value := range s.pendingStorage { 311 // Skip noop changes, persist actual changes 312 if value == s.originStorage[key] { 313 continue 314 } 315 s.originStorage[key] = value 316 317 if (value == common.Hash{}) { 318 s.setError(tr.TryDelete(key[:])) 319 continue 320 } 321 // Encoding []byte cannot fail, ok to ignore the error. 322 v, _ := rlp.EncodeToBytes(common.TrimLeftZeroes(value[:])) 323 s.setError(tr.TryUpdate(key[:], v)) 324 } 325 if len(s.pendingStorage) > 0 { 326 s.pendingStorage = make(Storage) 327 } 328 return tr 329 } 330 331 // UpdateRoot sets the trie root to the current root hash of 332 func (s *stateObject) updateRoot(db Database) { 333 s.updateTrie(db) 334 335 // Track the amount of time wasted on hashing the storge trie 336 if metrics.EnabledExpensive { 337 defer func(start time.Time) { s.db.StorageHashes += time.Since(start) }(time.Now()) 338 } 339 s.data.Root = s.trie.Hash() 340 } 341 342 // CommitTrie the storage trie of the object to db. 343 // This updates the trie root. 344 func (s *stateObject) CommitTrie(db Database) error { 345 s.updateTrie(db) 346 if s.dbErr != nil { 347 return s.dbErr 348 } 349 // Track the amount of time wasted on committing the storge trie 350 if metrics.EnabledExpensive { 351 defer func(start time.Time) { s.db.StorageCommits += time.Since(start) }(time.Now()) 352 } 353 root, err := s.trie.Commit(nil) 354 if err == nil { 355 s.data.Root = root 356 } 357 return err 358 } 359 360 // AddBalance removes amount from c's balance. 361 // It is used to add funds to the destination account of a transfer. 362 func (s *stateObject) AddBalance(amount *big.Int) { 363 // EIP158: We must check emptiness for the objects such that the account 364 // clearing (0,0,0 objects) can take effect. 365 if amount.Sign() == 0 { 366 if s.empty() { 367 s.touch() 368 } 369 370 return 371 } 372 s.SetBalance(new(big.Int).Add(s.Balance(), amount)) 373 } 374 375 // SubBalance removes amount from c's balance. 376 // It is used to remove funds from the origin account of a transfer. 377 func (s *stateObject) SubBalance(amount *big.Int) { 378 if amount.Sign() == 0 { 379 return 380 } 381 s.SetBalance(new(big.Int).Sub(s.Balance(), amount)) 382 } 383 384 func (s *stateObject) SetBalance(amount *big.Int) { 385 s.db.journal.append(balanceChange{ 386 account: &s.address, 387 prev: new(big.Int).Set(s.data.Balance), 388 }) 389 s.setBalance(amount) 390 } 391 392 func (s *stateObject) setBalance(amount *big.Int) { 393 s.data.Balance = amount 394 } 395 396 // Return the gas back to the origin. Used by the Virtual machine or Closures 397 func (s *stateObject) ReturnGas(gas *big.Int) {} 398 399 func (s *stateObject) deepCopy(db *StateDB) *stateObject { 400 stateObject := newObject(db, s.address, s.data) 401 if s.trie != nil { 402 stateObject.trie = db.db.CopyTrie(s.trie) 403 } 404 stateObject.code = s.code 405 stateObject.dirtyStorage = s.dirtyStorage.Copy() 406 stateObject.originStorage = s.originStorage.Copy() 407 stateObject.pendingStorage = s.pendingStorage.Copy() 408 stateObject.suicided = s.suicided 409 stateObject.dirtyCode = s.dirtyCode 410 stateObject.deleted = s.deleted 411 // Quorum - Privacy Enhancements - copy privacy metadata fields 412 stateObject.privacyMetadata = s.privacyMetadata 413 stateObject.dirtyPrivacyMetadata = s.dirtyPrivacyMetadata 414 415 return stateObject 416 } 417 418 // 419 // Attribute accessors 420 // 421 422 // Returns the address of the contract/account 423 func (s *stateObject) Address() common.Address { 424 return s.address 425 } 426 427 // Code returns the contract code associated with this object, if any. 428 func (s *stateObject) Code(db Database) []byte { 429 if s.code != nil { 430 return s.code 431 } 432 if bytes.Equal(s.CodeHash(), emptyCodeHash) { 433 return nil 434 } 435 code, err := db.ContractCode(s.addrHash, common.BytesToHash(s.CodeHash())) 436 if err != nil { 437 s.setError(fmt.Errorf("can't load code hash %x: %v", s.CodeHash(), err)) 438 } 439 s.code = code 440 return code 441 } 442 443 func (s *stateObject) SetCode(codeHash common.Hash, code []byte) { 444 prevcode := s.Code(s.db.db) 445 s.db.journal.append(codeChange{ 446 account: &s.address, 447 prevhash: s.CodeHash(), 448 prevcode: prevcode, 449 }) 450 s.setCode(codeHash, code) 451 } 452 453 func (s *stateObject) setCode(codeHash common.Hash, code []byte) { 454 s.code = code 455 s.data.CodeHash = codeHash[:] 456 s.dirtyCode = true 457 } 458 459 func (s *stateObject) SetNonce(nonce uint64) { 460 s.db.journal.append(nonceChange{ 461 account: &s.address, 462 prev: s.data.Nonce, 463 }) 464 s.setNonce(nonce) 465 } 466 467 func (s *stateObject) setNonce(nonce uint64) { 468 s.data.Nonce = nonce 469 } 470 471 // Quorum - Privacy Enhancements 472 func (s *stateObject) SetStatePrivacyMetadata(metadata *PrivacyMetadata) { 473 prevPM, _ := s.PrivacyMetadata() 474 s.db.journal.append(privacyMetadataChange{ 475 account: &s.address, 476 prev: prevPM, 477 }) 478 s.setStatePrivacyMetadata(metadata) 479 } 480 481 func (s *stateObject) setStatePrivacyMetadata(metadata *PrivacyMetadata) { 482 s.privacyMetadata = metadata 483 s.dirtyPrivacyMetadata = true 484 } 485 486 // End Quorum - Privacy Enhancements 487 488 func (s *stateObject) CodeHash() []byte { 489 return s.data.CodeHash 490 } 491 492 func (s *stateObject) Balance() *big.Int { 493 return s.data.Balance 494 } 495 496 func (s *stateObject) Nonce() uint64 { 497 return s.data.Nonce 498 } 499 500 // Quorum - Privacy Enhancements 501 func (s *stateObject) PrivacyMetadata() (*PrivacyMetadata, error) { 502 if s.privacyMetadata != nil { 503 return s.privacyMetadata, nil 504 } 505 val, err := s.GetCommittedPrivacyMetadata() 506 if val != nil { 507 s.privacyMetadata = val 508 } 509 return val, err 510 } 511 512 func (s *stateObject) GetCommittedPrivacyMetadata() (*PrivacyMetadata, error) { 513 val, err := s.db.privacyMetaDataTrie.TryGet(s.address.Bytes()) 514 if err != nil { 515 return nil, fmt.Errorf("unable to retrieve metadata from the privacyMetadataTrie. Cause: %v", err) 516 } 517 if len(val) == 0 { 518 return nil, fmt.Errorf("The provided contract does not have privacy metadata: %x", s.address) 519 } 520 return bytesToPrivacyMetadata(val) 521 } 522 523 // End Quorum - Privacy Enhancements 524 525 // Never called, but must be present to allow stateObject to be used 526 // as a vm.Account interface that also satisfies the vm.ContractRef 527 // interface. Interfaces are awesome. 528 func (s *stateObject) Value() *big.Int { 529 panic("Value on stateObject should never be called") 530 } 531 532 // Quorum - Privacy Enhancements 533 func privacyMetadataToBytes(pm *PrivacyMetadata) ([]byte, error) { 534 return rlp.EncodeToBytes(pm) 535 } 536 537 func bytesToPrivacyMetadata(b []byte) (*PrivacyMetadata, error) { 538 var data *PrivacyMetadata 539 if err := rlp.DecodeBytes(b, &data); err != nil { 540 return nil, fmt.Errorf("unable to decode privacy metadata. Cause: %v", err) 541 } 542 return data, nil 543 } 544 545 // End Quorum - Privacy Enhancements