statedb.go 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. // Package state provides a caching layer atop the Ethereum state trie.
  17. package state
  18. import (
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "sort"
  23. "sync"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/state/snapshot"
  28. "github.com/ethereum/go-ethereum/core/types"
  29. "github.com/ethereum/go-ethereum/crypto"
  30. "github.com/ethereum/go-ethereum/log"
  31. "github.com/ethereum/go-ethereum/metrics"
  32. "github.com/ethereum/go-ethereum/rlp"
  33. "github.com/ethereum/go-ethereum/trie"
  34. )
  35. type revision struct {
  36. id int
  37. journalIndex int
  38. }
  39. var (
  40. // emptyRoot is the known root hash of an empty trie.
  41. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  42. )
  43. type proofList [][]byte
  44. func (n *proofList) Put(key []byte, value []byte) error {
  45. *n = append(*n, value)
  46. return nil
  47. }
  48. func (n *proofList) Delete(key []byte) error {
  49. panic("not supported")
  50. }
  51. // StateDB structs within the ethereum protocol are used to store anything
  52. // within the merkle trie. StateDBs take care of caching and storing
  53. // nested states. It's the general query interface to retrieve:
  54. // * Contracts
  55. // * Accounts
  56. type StateDB struct {
  57. db Database
  58. prefetcher *triePrefetcher
  59. originalRoot common.Hash // The pre-state root, before any changes were made
  60. trie Trie
  61. hasher crypto.KeccakState
  62. snaps *snapshot.Tree
  63. snap snapshot.Snapshot
  64. snapDestructs map[common.Hash]struct{}
  65. snapAccounts map[common.Hash][]byte
  66. snapStorage map[common.Hash]map[common.Hash][]byte
  67. mutex sync.Mutex
  68. journalMutex sync.Mutex
  69. // Quorum - a trie to hold extra account information that cannot be stored in the accounts trie
  70. accountExtraDataTrie Trie
  71. // This map holds 'live' objects, which will get modified while processing a state transition.
  72. stateObjects map[common.Address]*stateObject
  73. stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
  74. stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution
  75. // DB error.
  76. // State objects are used by the consensus core and VM which are
  77. // unable to deal with database-level errors. Any error that occurs
  78. // during a database read is memoized here and will eventually be returned
  79. // by StateDB.Commit.
  80. dbErr error
  81. // The refund counter, also used by state transitioning.
  82. refund uint64
  83. thash, bhash common.Hash
  84. txIndex int
  85. logs map[common.Hash][]*types.Log
  86. logSize uint
  87. preimages map[common.Hash][]byte
  88. // Per-transaction access list
  89. accessList *accessList
  90. // Journal of state modifications. This is the backbone of
  91. // Snapshot and RevertToSnapshot.
  92. journal *journal
  93. validRevisions []revision
  94. nextRevisionId int
  95. // Measurements gathered during execution for debugging purposes
  96. AccountReads time.Duration
  97. AccountHashes time.Duration
  98. AccountUpdates time.Duration
  99. AccountCommits time.Duration
  100. StorageReads time.Duration
  101. StorageHashes time.Duration
  102. StorageUpdates time.Duration
  103. StorageCommits time.Duration
  104. SnapshotAccountReads time.Duration
  105. SnapshotStorageReads time.Duration
  106. SnapshotCommits time.Duration
  107. }
  108. // New creates a new state from a given trie.
  109. func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
  110. tr, err := db.OpenTrie(root)
  111. if err != nil {
  112. return nil, err
  113. }
  114. // Quorum - Privacy Enhancements - retrieve the privacy metadata root corresponding to the account state root
  115. extraDataRoot := db.AccountExtraDataLinker().GetAccountExtraDataRoot(root)
  116. log.Debug("Account Extra Data root", "hash", extraDataRoot)
  117. accountExtraDataTrie, err := db.OpenTrie(extraDataRoot)
  118. if err != nil {
  119. return nil, fmt.Errorf("Unable to open privacy metadata trie: %v", err)
  120. }
  121. // End Quorum - Privacy Enhancements
  122. sdb := &StateDB{
  123. db: db,
  124. trie: tr,
  125. originalRoot: root,
  126. snaps: snaps,
  127. stateObjects: make(map[common.Address]*stateObject),
  128. stateObjectsPending: make(map[common.Address]struct{}),
  129. stateObjectsDirty: make(map[common.Address]struct{}),
  130. logs: make(map[common.Hash][]*types.Log),
  131. preimages: make(map[common.Hash][]byte),
  132. journal: newJournal(),
  133. accessList: newAccessList(),
  134. hasher: crypto.NewKeccakState(),
  135. // Quorum - Privacy Enhancements
  136. accountExtraDataTrie: accountExtraDataTrie,
  137. }
  138. if sdb.snaps != nil {
  139. if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
  140. sdb.snapDestructs = make(map[common.Hash]struct{})
  141. sdb.snapAccounts = make(map[common.Hash][]byte)
  142. sdb.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
  143. }
  144. }
  145. return sdb, nil
  146. }
  147. // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the
  148. // state trie concurrently while the state is mutated so that when we reach the
  149. // commit phase, most of the needed data is already hot.
  150. func (s *StateDB) StartPrefetcher(namespace string) {
  151. if s.prefetcher != nil {
  152. s.prefetcher.close()
  153. s.prefetcher = nil
  154. }
  155. if s.snap != nil {
  156. s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace)
  157. }
  158. }
  159. // StopPrefetcher terminates a running prefetcher and reports any leftover stats
  160. // from the gathered metrics.
  161. func (s *StateDB) StopPrefetcher() {
  162. if s.prefetcher != nil {
  163. s.prefetcher.close()
  164. s.prefetcher = nil
  165. }
  166. }
  167. // setError remembers the first non-nil error it is called with.
  168. func (s *StateDB) setError(err error) {
  169. if s.dbErr == nil {
  170. s.dbErr = err
  171. }
  172. }
  173. func (s *StateDB) Error() error {
  174. return s.dbErr
  175. }
  176. func (s *StateDB) AddLog(log *types.Log) {
  177. s.journal.append(addLogChange{txhash: s.thash})
  178. log.TxHash = s.thash
  179. log.BlockHash = s.bhash
  180. log.TxIndex = uint(s.txIndex)
  181. log.Index = s.logSize
  182. s.logs[s.thash] = append(s.logs[s.thash], log)
  183. s.logSize++
  184. }
  185. func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
  186. return s.logs[hash]
  187. }
  188. func (s *StateDB) Logs() []*types.Log {
  189. var logs []*types.Log
  190. for _, lgs := range s.logs {
  191. logs = append(logs, lgs...)
  192. }
  193. return logs
  194. }
  195. // AddPreimage records a SHA3 preimage seen by the VM.
  196. func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
  197. if _, ok := s.preimages[hash]; !ok {
  198. s.journal.append(addPreimageChange{hash: hash})
  199. pi := make([]byte, len(preimage))
  200. copy(pi, preimage)
  201. s.preimages[hash] = pi
  202. }
  203. }
  204. // Preimages returns a list of SHA3 preimages that have been submitted.
  205. func (s *StateDB) Preimages() map[common.Hash][]byte {
  206. return s.preimages
  207. }
  208. // AddRefund adds gas to the refund counter
  209. func (s *StateDB) AddRefund(gas uint64) {
  210. s.journal.append(refundChange{prev: s.refund})
  211. s.refund += gas
  212. }
  213. // SubRefund removes gas from the refund counter.
  214. // This method will panic if the refund counter goes below zero
  215. func (s *StateDB) SubRefund(gas uint64) {
  216. s.journal.append(refundChange{prev: s.refund})
  217. if gas > s.refund {
  218. panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
  219. }
  220. s.refund -= gas
  221. }
  222. // Exist reports whether the given account address exists in the state.
  223. // Notably this also returns true for suicided accounts.
  224. func (s *StateDB) Exist(addr common.Address) bool {
  225. return s.getStateObject(addr) != nil
  226. }
  227. // Empty returns whether the state object is either non-existent
  228. // or empty according to the EIP161 specification (balance = nonce = code = 0)
  229. func (s *StateDB) Empty(addr common.Address) bool {
  230. so := s.getStateObject(addr)
  231. return so == nil || so.empty()
  232. }
  233. // GetBalance retrieves the balance from the given address or 0 if object not found
  234. func (s *StateDB) GetBalance(addr common.Address) *big.Int {
  235. stateObject := s.getStateObject(addr)
  236. if stateObject != nil {
  237. return stateObject.Balance()
  238. }
  239. return common.Big0
  240. }
  241. func (s *StateDB) GetNonce(addr common.Address) uint64 {
  242. stateObject := s.getStateObject(addr)
  243. if stateObject != nil {
  244. return stateObject.Nonce()
  245. }
  246. return 0
  247. }
  248. // Quorum
  249. func (s *StateDB) GetPrivacyMetadata(addr common.Address) (*PrivacyMetadata, error) {
  250. stateObject := s.getStateObject(addr)
  251. if stateObject != nil {
  252. return stateObject.PrivacyMetadata()
  253. }
  254. return nil, nil
  255. }
  256. // Quorum
  257. func (s *StateDB) GetCommittedStatePrivacyMetadata(addr common.Address) (*PrivacyMetadata, error) {
  258. stateObject := s.getStateObject(addr)
  259. if stateObject != nil {
  260. return stateObject.GetCommittedPrivacyMetadata()
  261. }
  262. return nil, nil
  263. }
  264. // Quorum
  265. func (self *StateDB) GetManagedParties(addr common.Address) ([]string, error) {
  266. stateObject := self.getStateObject(addr)
  267. if stateObject != nil {
  268. return stateObject.ManagedParties()
  269. }
  270. return nil, nil
  271. }
  272. func (s *StateDB) GetRLPEncodedStateObject(addr common.Address) ([]byte, error) {
  273. stateObject := s.getStateObject(addr)
  274. if stateObject == nil {
  275. return nil, fmt.Errorf("no state found for %s", addr.Hex())
  276. }
  277. // When calculating the execution hash or simulating the transaction the stateOject state is not committed/updated
  278. // In order to reflect the updated state invoke stateObject.updateRoot on a copy of the state object.
  279. if len(stateObject.pendingStorage) > 0 || len(stateObject.dirtyStorage) > 0 || stateObject.dirtyCode {
  280. cpy := stateObject.deepCopy(s)
  281. cpy.updateRoot(s.db)
  282. return rlp.EncodeToBytes(cpy)
  283. }
  284. return rlp.EncodeToBytes(stateObject)
  285. }
  286. // Reset clears out all ephemeral state objects from the state db, but keeps
  287. // the underlying state trie to avoid reloading data for the next operations.
  288. func (s *StateDB) Reset(root common.Hash) error {
  289. tr, err := s.db.OpenTrie(root)
  290. if err != nil {
  291. return err
  292. }
  293. s.trie = tr
  294. s.mutex.Lock()
  295. s.stateObjects = make(map[common.Address]*stateObject)
  296. s.stateObjectsPending = make(map[common.Address]struct{})
  297. s.stateObjectsDirty = make(map[common.Address]struct{})
  298. s.mutex.Unlock()
  299. s.thash = common.Hash{}
  300. s.bhash = common.Hash{}
  301. s.txIndex = 0
  302. s.logs = make(map[common.Hash][]*types.Log)
  303. s.logSize = 0
  304. s.preimages = make(map[common.Hash][]byte)
  305. s.clearJournalAndRefund()
  306. if s.snaps != nil {
  307. s.snapAccounts, s.snapDestructs, s.snapStorage = nil, nil, nil
  308. if s.snap = s.snaps.Snapshot(root); s.snap != nil {
  309. s.snapDestructs = make(map[common.Hash]struct{})
  310. s.snapAccounts = make(map[common.Hash][]byte)
  311. s.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
  312. }
  313. }
  314. s.accessList = newAccessList()
  315. return nil
  316. }
  317. // End Quorum
  318. // TxIndex returns the current transaction index set by Prepare.
  319. func (s *StateDB) TxIndex() int {
  320. return s.txIndex
  321. }
  322. // BlockHash returns the current block hash set by Prepare.
  323. func (s *StateDB) BlockHash() common.Hash {
  324. return s.bhash
  325. }
  326. func (s *StateDB) GetCode(addr common.Address) []byte {
  327. stateObject := s.getStateObject(addr)
  328. if stateObject != nil {
  329. return stateObject.Code(s.db)
  330. }
  331. return nil
  332. }
  333. func (s *StateDB) GetCodeSize(addr common.Address) int {
  334. stateObject := s.getStateObject(addr)
  335. if stateObject != nil {
  336. return stateObject.CodeSize(s.db)
  337. }
  338. return 0
  339. }
  340. func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
  341. stateObject := s.getStateObject(addr)
  342. if stateObject == nil {
  343. return common.Hash{}
  344. }
  345. return common.BytesToHash(stateObject.CodeHash())
  346. }
  347. // GetState retrieves a value from the given account's storage trie.
  348. func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
  349. stateObject := s.getStateObject(addr)
  350. if stateObject != nil {
  351. return stateObject.GetState(s.db, hash)
  352. }
  353. return common.Hash{}
  354. }
  355. // GetProof returns the Merkle proof for a given account.
  356. func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) {
  357. return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes()))
  358. }
  359. // GetProofByHash returns the Merkle proof for a given account.
  360. func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) {
  361. var proof proofList
  362. err := s.trie.Prove(addrHash[:], 0, &proof)
  363. return proof, err
  364. }
  365. // GetStorageProof returns the Merkle proof for given storage slot.
  366. func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
  367. var proof proofList
  368. trie := s.StorageTrie(a)
  369. if trie == nil {
  370. return proof, errors.New("storage trie for requested address does not exist")
  371. }
  372. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  373. return proof, err
  374. }
  375. // GetStorageProofByHash returns the Merkle proof for given storage slot.
  376. func (s *StateDB) GetStorageProofByHash(a common.Address, key common.Hash) ([][]byte, error) {
  377. var proof proofList
  378. trie := s.StorageTrie(a)
  379. if trie == nil {
  380. return proof, errors.New("storage trie for requested address does not exist")
  381. }
  382. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  383. return proof, err
  384. }
  385. // GetCommittedState retrieves a value from the given account's committed storage trie.
  386. func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
  387. stateObject := s.getStateObject(addr)
  388. if stateObject != nil {
  389. return stateObject.GetCommittedState(s.db, hash)
  390. }
  391. return common.Hash{}
  392. }
  393. // Database retrieves the low level database supporting the lower level trie ops.
  394. func (s *StateDB) Database() Database {
  395. return s.db
  396. }
  397. // StorageTrie returns the storage trie of an account.
  398. // The return value is a copy and is nil for non-existent accounts.
  399. func (s *StateDB) StorageTrie(addr common.Address) Trie {
  400. stateObject := s.getStateObject(addr)
  401. if stateObject == nil {
  402. return nil
  403. }
  404. cpy := stateObject.deepCopy(s)
  405. cpy.updateTrie(s.db)
  406. return cpy.getTrie(s.db)
  407. }
  408. func (s *StateDB) HasSuicided(addr common.Address) bool {
  409. stateObject := s.getStateObject(addr)
  410. if stateObject != nil {
  411. return stateObject.suicided
  412. }
  413. return false
  414. }
  415. // Quorum
  416. // GetStorageRoot returns the root of the storage associated with the given address.
  417. func (s *StateDB) GetStorageRoot(addr common.Address) (common.Hash, error) {
  418. so := s.getStateObject(addr)
  419. if so == nil {
  420. return common.Hash{}, fmt.Errorf("can't find state object")
  421. }
  422. return so.storageRoot(s.db), nil
  423. }
  424. /*
  425. * SETTERS
  426. */
  427. // AddBalance adds amount to the account associated with addr.
  428. func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  429. stateObject := s.GetOrNewStateObject(addr)
  430. if stateObject != nil {
  431. stateObject.AddBalance(amount)
  432. }
  433. }
  434. // SubBalance subtracts amount from the account associated with addr.
  435. func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
  436. stateObject := s.GetOrNewStateObject(addr)
  437. if stateObject != nil {
  438. stateObject.SubBalance(amount)
  439. }
  440. }
  441. func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  442. stateObject := s.GetOrNewStateObject(addr)
  443. if stateObject != nil {
  444. stateObject.SetBalance(amount)
  445. }
  446. }
  447. func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
  448. stateObject := s.GetOrNewStateObject(addr)
  449. if stateObject != nil {
  450. stateObject.SetNonce(nonce)
  451. }
  452. }
  453. func (s *StateDB) SetPrivacyMetadata(addr common.Address, metadata *PrivacyMetadata) {
  454. stateObject := s.GetOrNewStateObject(addr)
  455. if stateObject != nil {
  456. stateObject.SetStatePrivacyMetadata(metadata)
  457. }
  458. }
  459. func (self *StateDB) SetManagedParties(addr common.Address, managedParties []string) {
  460. stateObject := self.GetOrNewStateObject(addr)
  461. if stateObject != nil && len(managedParties) > 0 {
  462. stateObject.SetManagedParties(managedParties)
  463. }
  464. }
  465. func (s *StateDB) SetCode(addr common.Address, code []byte) {
  466. stateObject := s.GetOrNewStateObject(addr)
  467. if stateObject != nil {
  468. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  469. }
  470. }
  471. func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
  472. stateObject := s.GetOrNewStateObject(addr)
  473. if stateObject != nil {
  474. stateObject.SetState(s.db, key, value)
  475. }
  476. }
  477. // SetStorage replaces the entire storage for the specified account with given
  478. // storage. This function should only be used for debugging.
  479. func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
  480. stateObject := s.GetOrNewStateObject(addr)
  481. if stateObject != nil {
  482. stateObject.SetStorage(storage)
  483. }
  484. }
  485. // Suicide marks the given account as suicided.
  486. // This clears the account balance.
  487. //
  488. // The account's state object is still available until the state is committed,
  489. // getStateObject will return a non-nil account after Suicide.
  490. func (s *StateDB) Suicide(addr common.Address) bool {
  491. stateObject := s.getStateObject(addr)
  492. if stateObject == nil {
  493. return false
  494. }
  495. s.journal.append(suicideChange{
  496. account: &addr,
  497. prev: stateObject.suicided,
  498. prevbalance: new(big.Int).Set(stateObject.Balance()),
  499. })
  500. stateObject.markSuicided()
  501. stateObject.data.Balance = new(big.Int)
  502. return true
  503. }
  504. //
  505. // Setting, updating & deleting state object methods.
  506. //
  507. // updateStateObject writes the given object to the trie.
  508. // Quorum:
  509. // - update AccountExtraData trie
  510. func (s *StateDB) updateStateObject(obj *stateObject) {
  511. // Track the amount of time wasted on updating the account from the trie
  512. if metrics.EnabledExpensive {
  513. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  514. }
  515. // Encode the account and update the account trie
  516. addr := obj.Address()
  517. data, err := rlp.EncodeToBytes(obj)
  518. if err != nil {
  519. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  520. }
  521. if err = s.trie.TryUpdate(addr[:], data); err != nil {
  522. s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
  523. }
  524. // If state snapshotting is active, cache the data til commit. Note, this
  525. // update mechanism is not symmetric to the deletion, because whereas it is
  526. // enough to track account updates at commit time, deletions need tracking
  527. // at transaction boundary level to ensure we capture state clearing.
  528. if s.snap != nil {
  529. s.snapAccounts[obj.addrHash] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash)
  530. }
  531. // Quorum - Privacy Enhancements - update the privacy metadata trie in case the privacy metadata is dirty
  532. if err != nil {
  533. return
  534. }
  535. if obj.dirtyAccountExtraData && obj.accountExtraData != nil {
  536. extraDataBytes, err := rlp.EncodeToBytes(obj.accountExtraData)
  537. if err != nil {
  538. panic(fmt.Errorf("can't encode privacy metadata at %x: %v", addr[:], err))
  539. }
  540. err = s.accountExtraDataTrie.TryUpdate(addr[:], extraDataBytes)
  541. if err != nil {
  542. s.setError(err)
  543. return
  544. }
  545. }
  546. }
  547. // deleteStateObject removes the given object from the state trie.
  548. // Quorum:
  549. // - delete the data from the extra data trie corresponding to the account address
  550. func (s *StateDB) deleteStateObject(obj *stateObject) {
  551. // Track the amount of time wasted on deleting the account from the trie
  552. if metrics.EnabledExpensive {
  553. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  554. }
  555. // Delete the account from the trie
  556. addr := obj.Address()
  557. if err := s.trie.TryDelete(addr[:]); err != nil {
  558. s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
  559. return
  560. }
  561. s.setError(s.accountExtraDataTrie.TryDelete(addr[:]))
  562. }
  563. // getStateObject retrieves a state object given by the address, returning nil if
  564. // the object is not found or was deleted in this execution context. If you need
  565. // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
  566. func (s *StateDB) getStateObject(addr common.Address) *stateObject {
  567. if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
  568. return obj
  569. }
  570. return nil
  571. }
  572. // getDeletedStateObject is similar to getStateObject, but instead of returning
  573. // nil for a deleted state object, it returns the actual object with the deleted
  574. // flag set. This is needed by the state journal to revert to the correct s-
  575. // destructed object instead of wiping all knowledge about the state object.
  576. func (s *StateDB) getDeletedStateObject(addr common.Address) *stateObject {
  577. // Prefer live objects if any is available
  578. if obj := s.stateObjects[addr]; obj != nil {
  579. return obj
  580. }
  581. // If no live objects are available, attempt to use snapshots
  582. var (
  583. data *Account
  584. err error
  585. )
  586. if s.snap != nil {
  587. if metrics.EnabledExpensive {
  588. defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now())
  589. }
  590. var acc *snapshot.Account
  591. if acc, err = s.snap.Account(crypto.HashData(s.hasher, addr.Bytes())); err == nil {
  592. if acc == nil {
  593. return nil
  594. }
  595. data = &Account{
  596. Nonce: acc.Nonce,
  597. Balance: acc.Balance,
  598. CodeHash: acc.CodeHash,
  599. Root: common.BytesToHash(acc.Root),
  600. }
  601. if len(data.CodeHash) == 0 {
  602. data.CodeHash = emptyCodeHash
  603. }
  604. if data.Root == (common.Hash{}) {
  605. data.Root = emptyRoot
  606. }
  607. }
  608. }
  609. // If snapshot unavailable or reading from it failed, load from the database
  610. if s.snap == nil || err != nil {
  611. if metrics.EnabledExpensive {
  612. defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
  613. }
  614. enc, err := s.trie.TryGet(addr.Bytes())
  615. if err != nil {
  616. s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err))
  617. return nil
  618. }
  619. if len(enc) == 0 {
  620. return nil
  621. }
  622. data = new(Account)
  623. if err := rlp.DecodeBytes(enc, data); err != nil {
  624. log.Error("Failed to decode state object", "addr", addr, "err", err)
  625. return nil
  626. }
  627. }
  628. // Insert into the live set
  629. obj := newObject(s, addr, *data)
  630. s.setStateObject(obj)
  631. return obj
  632. }
  633. func (s *StateDB) setStateObject(object *stateObject) {
  634. defer s.mutex.Unlock()
  635. s.mutex.Lock()
  636. s.stateObjects[object.Address()] = object
  637. }
  638. // GetOrNewStateObject retrieves a state object or create a new state object if nil.
  639. func (s *StateDB) GetOrNewStateObject(addr common.Address) *stateObject {
  640. stateObject := s.getStateObject(addr)
  641. if stateObject == nil {
  642. stateObject, _ = s.createObject(addr)
  643. }
  644. return stateObject
  645. }
  646. // createObject creates a new state object. If there is an existing account with
  647. // the given address, it is overwritten and returned as the second return value.
  648. func (s *StateDB) createObject(addr common.Address) (newobj, prev *stateObject) {
  649. prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
  650. var prevdestruct bool
  651. if s.snap != nil && prev != nil {
  652. _, prevdestruct = s.snapDestructs[prev.addrHash]
  653. if !prevdestruct {
  654. s.snapDestructs[prev.addrHash] = struct{}{}
  655. }
  656. }
  657. newobj = newObject(s, addr, Account{})
  658. newobj.setNonce(0) // sets the object to dirty
  659. if prev == nil {
  660. s.journal.append(createObjectChange{account: &addr})
  661. } else {
  662. s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
  663. }
  664. s.setStateObject(newobj)
  665. if prev != nil && !prev.deleted {
  666. return newobj, prev
  667. }
  668. return newobj, nil
  669. }
  670. // CreateAccount explicitly creates a state object. If a state object with the address
  671. // already exists the balance is carried over to the new account.
  672. //
  673. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  674. // a contract does the following:
  675. //
  676. // 1. sends funds to sha(account ++ (nonce + 1))
  677. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  678. //
  679. // Carrying over the balance ensures that Ether doesn't disappear.
  680. func (s *StateDB) CreateAccount(addr common.Address) {
  681. newObj, prev := s.createObject(addr)
  682. if prev != nil {
  683. newObj.setBalance(prev.data.Balance)
  684. }
  685. }
  686. func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
  687. so := db.getStateObject(addr)
  688. if so == nil {
  689. return nil
  690. }
  691. it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
  692. for it.Next() {
  693. key := common.BytesToHash(db.trie.GetKey(it.Key))
  694. if value, dirty := so.dirtyStorage[key]; dirty {
  695. if !cb(key, value) {
  696. return nil
  697. }
  698. continue
  699. }
  700. if len(it.Value) > 0 {
  701. _, content, _, err := rlp.Split(it.Value)
  702. if err != nil {
  703. return err
  704. }
  705. if !cb(key, common.BytesToHash(content)) {
  706. return nil
  707. }
  708. }
  709. }
  710. return nil
  711. }
  712. // Copy creates a deep, independent copy of the state.
  713. // Snapshots of the copied state cannot be applied to the copy.
  714. func (s *StateDB) Copy() *StateDB {
  715. s.journalMutex.Lock()
  716. journal := s.journal
  717. s.journalMutex.Unlock()
  718. journal.mutex.Lock()
  719. size := len(journal.dirties)
  720. dirties := make([]common.Address, 0, size)
  721. for addr := range journal.dirties {
  722. dirties = append(dirties, addr)
  723. }
  724. journal.mutex.Unlock()
  725. // Copy all the basic fields, initialize the memory ones
  726. state := &StateDB{
  727. db: s.db,
  728. trie: s.db.CopyTrie(s.trie),
  729. stateObjects: make(map[common.Address]*stateObject, size),
  730. stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
  731. stateObjectsDirty: make(map[common.Address]struct{}, size),
  732. refund: s.refund,
  733. logs: make(map[common.Hash][]*types.Log, len(s.logs)),
  734. logSize: s.logSize,
  735. preimages: make(map[common.Hash][]byte, len(s.preimages)),
  736. journal: newJournal(),
  737. hasher: crypto.NewKeccakState(),
  738. // Quorum - Privacy Enhancements
  739. accountExtraDataTrie: s.db.CopyTrie(s.accountExtraDataTrie),
  740. }
  741. s.mutex.Lock()
  742. // Copy the dirty states, logs, and preimages
  743. for _, addr := range dirties {
  744. // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
  745. // and in the Finalise-method, there is a case where an object is in the journal but not
  746. // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
  747. // nil
  748. if object, exist := s.stateObjects[addr]; exist {
  749. // Even though the original object is dirty, we are not copying the journal,
  750. // so we need to make sure that anyside effect the journal would have caused
  751. // during a commit (or similar op) is already applied to the copy.
  752. state.stateObjects[addr] = object.deepCopy(state)
  753. state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits
  754. state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
  755. }
  756. }
  757. // Above, we don't copy the actual journal. This means that if the copy is copied, the
  758. // loop above will be a no-op, since the copy's journal is empty.
  759. // Thus, here we iterate over stateObjects, to enable copies of copies
  760. for addr := range s.stateObjectsPending {
  761. if _, exist := state.stateObjects[addr]; !exist {
  762. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  763. }
  764. state.stateObjectsPending[addr] = struct{}{}
  765. }
  766. for addr := range s.stateObjectsDirty {
  767. if _, exist := state.stateObjects[addr]; !exist {
  768. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  769. }
  770. state.stateObjectsDirty[addr] = struct{}{}
  771. }
  772. s.mutex.Unlock()
  773. for hash, logs := range s.logs {
  774. cpy := make([]*types.Log, len(logs))
  775. for i, l := range logs {
  776. cpy[i] = new(types.Log)
  777. *cpy[i] = *l
  778. }
  779. state.logs[hash] = cpy
  780. }
  781. for hash, preimage := range s.preimages {
  782. state.preimages[hash] = preimage
  783. }
  784. // Do we need to copy the access list? In practice: No. At the start of a
  785. // transaction, the access list is empty. In practice, we only ever copy state
  786. // _between_ transactions/blocks, never in the middle of a transaction.
  787. // However, it doesn't cost us much to copy an empty list, so we do it anyway
  788. // to not blow up if we ever decide copy it in the middle of a transaction
  789. state.accessList = s.accessList.Copy()
  790. // If there's a prefetcher running, make an inactive copy of it that can
  791. // only access data but does not actively preload (since the user will not
  792. // know that they need to explicitly terminate an active copy).
  793. if s.prefetcher != nil {
  794. state.prefetcher = s.prefetcher.copy()
  795. }
  796. if s.snaps != nil {
  797. // In order for the miner to be able to use and make additions
  798. // to the snapshot tree, we need to copy that aswell.
  799. // Otherwise, any block mined by ourselves will cause gaps in the tree,
  800. // and force the miner to operate trie-backed only
  801. state.snaps = s.snaps
  802. state.snap = s.snap
  803. // deep copy needed
  804. state.snapDestructs = make(map[common.Hash]struct{})
  805. for k, v := range s.snapDestructs {
  806. state.snapDestructs[k] = v
  807. }
  808. state.snapAccounts = make(map[common.Hash][]byte)
  809. for k, v := range s.snapAccounts {
  810. state.snapAccounts[k] = v
  811. }
  812. state.snapStorage = make(map[common.Hash]map[common.Hash][]byte)
  813. for k, v := range s.snapStorage {
  814. temp := make(map[common.Hash][]byte)
  815. for kk, vv := range v {
  816. temp[kk] = vv
  817. }
  818. state.snapStorage[k] = temp
  819. }
  820. }
  821. return state
  822. }
  823. // Snapshot returns an identifier for the current revision of the state.
  824. func (s *StateDB) Snapshot() int {
  825. id := s.nextRevisionId
  826. s.nextRevisionId++
  827. s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
  828. return id
  829. }
  830. // RevertToSnapshot reverts all state changes made since the given revision.
  831. func (s *StateDB) RevertToSnapshot(revid int) {
  832. // Find the snapshot in the stack of valid snapshots.
  833. idx := sort.Search(len(s.validRevisions), func(i int) bool {
  834. return s.validRevisions[i].id >= revid
  835. })
  836. if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
  837. panic(fmt.Errorf("revision id %v cannot be reverted", revid))
  838. }
  839. snapshot := s.validRevisions[idx].journalIndex
  840. // Replay the journal to undo changes and remove invalidated snapshots
  841. s.journal.revert(s, snapshot)
  842. s.validRevisions = s.validRevisions[:idx]
  843. }
  844. // GetRefund returns the current value of the refund counter.
  845. func (s *StateDB) GetRefund() uint64 {
  846. return s.refund
  847. }
  848. // Finalise finalises the state by removing the s destructed objects and clears
  849. // the journal as well as the refunds. Finalise, however, will not push any updates
  850. // into the tries just yet. Only IntermediateRoot or Commit will do that.
  851. func (s *StateDB) Finalise(deleteEmptyObjects bool) {
  852. addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties))
  853. s.journal.mutex.Lock()
  854. dirties := make([]common.Address, 0, len(s.journal.dirties))
  855. for addr := range s.journal.dirties {
  856. dirties = append(dirties, addr)
  857. }
  858. s.journal.mutex.Unlock()
  859. for _, addr := range dirties {
  860. obj, exist := s.stateObjects[addr]
  861. if !exist {
  862. // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
  863. // That tx goes out of gas, and although the notion of 'touched' does not exist there, the
  864. // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
  865. // it will persist in the journal even though the journal is reverted. In this special circumstance,
  866. // it may exist in `s.journal.dirties` but not in `s.stateObjects`.
  867. // Thus, we can safely ignore it here
  868. continue
  869. }
  870. if obj.suicided || (deleteEmptyObjects && obj.empty()) {
  871. obj.deleted = true
  872. // If state snapshotting is active, also mark the destruction there.
  873. // Note, we can't do this only at the end of a block because multiple
  874. // transactions within the same block might self destruct and then
  875. // ressurrect an account; but the snapshotter needs both events.
  876. if s.snap != nil {
  877. s.snapDestructs[obj.addrHash] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
  878. delete(s.snapAccounts, obj.addrHash) // Clear out any previously updated account data (may be recreated via a ressurrect)
  879. delete(s.snapStorage, obj.addrHash) // Clear out any previously updated storage data (may be recreated via a ressurrect)
  880. }
  881. } else {
  882. obj.finalise(true) // Prefetch slots in the background
  883. }
  884. s.mutex.Lock()
  885. s.stateObjectsPending[addr] = struct{}{}
  886. s.stateObjectsDirty[addr] = struct{}{}
  887. s.mutex.Unlock()
  888. // At this point, also ship the address off to the precacher. The precacher
  889. // will start loading tries, and when the change is eventually committed,
  890. // the commit-phase will be a lot faster
  891. addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure
  892. }
  893. if s.prefetcher != nil && len(addressesToPrefetch) > 0 {
  894. s.prefetcher.prefetch(s.originalRoot, addressesToPrefetch)
  895. }
  896. // Invalidate journal because reverting across transactions is not allowed.
  897. s.clearJournalAndRefund()
  898. }
  899. // IntermediateRoot computes the current root hash of the state trie.
  900. // It is called in between transactions to get the root hash that
  901. // goes into transaction receipts.
  902. func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
  903. // Finalise all the dirty storage states and write them into the tries
  904. s.Finalise(deleteEmptyObjects)
  905. s.mutex.Lock()
  906. defer s.mutex.Unlock()
  907. // If there was a trie prefetcher operating, it gets aborted and irrevocably
  908. // modified after we start retrieving tries. Remove it from the statedb after
  909. // this round of use.
  910. //
  911. // This is weird pre-byzantium since the first tx runs with a prefetcher and
  912. // the remainder without, but pre-byzantium even the initial prefetcher is
  913. // useless, so no sleep lost.
  914. prefetcher := s.prefetcher
  915. if s.prefetcher != nil {
  916. defer func() {
  917. s.prefetcher.close()
  918. s.prefetcher = nil
  919. }()
  920. }
  921. // Although naively it makes sense to retrieve the account trie and then do
  922. // the contract storage and account updates sequentially, that short circuits
  923. // the account prefetcher. Instead, let's process all the storage updates
  924. // first, giving the account prefeches just a few more milliseconds of time
  925. // to pull useful data from disk.
  926. for addr := range s.stateObjectsPending {
  927. if obj := s.stateObjects[addr]; !obj.deleted {
  928. obj.updateRoot(s.db)
  929. }
  930. }
  931. // Now we're about to start to write changes to the trie. The trie is so far
  932. // _untouched_. We can check with the prefetcher, if it can give us a trie
  933. // which has the same root, but also has some content loaded into it.
  934. if prefetcher != nil {
  935. if trie := prefetcher.trie(s.originalRoot); trie != nil {
  936. s.trie = trie
  937. }
  938. }
  939. usedAddrs := make([][]byte, 0, len(s.stateObjectsPending))
  940. for addr := range s.stateObjectsPending {
  941. if obj := s.stateObjects[addr]; obj.deleted {
  942. s.deleteStateObject(obj)
  943. } else {
  944. s.updateStateObject(obj)
  945. }
  946. usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure
  947. }
  948. if prefetcher != nil {
  949. prefetcher.used(s.originalRoot, usedAddrs)
  950. }
  951. if len(s.stateObjectsPending) > 0 {
  952. s.stateObjectsPending = make(map[common.Address]struct{})
  953. }
  954. // Track the amount of time wasted on hashing the account trie
  955. if metrics.EnabledExpensive {
  956. defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
  957. }
  958. return s.trie.Hash()
  959. }
  960. // Prepare sets the current transaction hash and index and block hash which is
  961. // used when the EVM emits new state logs.
  962. func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
  963. s.thash = thash
  964. s.bhash = bhash
  965. s.txIndex = ti
  966. s.accessList = newAccessList()
  967. }
  968. func (s *StateDB) clearJournalAndRefund() {
  969. defer s.journalMutex.Unlock()
  970. s.journalMutex.Lock()
  971. if len(s.journal.entries) > 0 {
  972. s.journal = newJournal()
  973. s.refund = 0
  974. }
  975. s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
  976. }
  977. // Commit writes the state to the underlying in-memory trie database.
  978. // Quorum:
  979. // - linking state root and the AccountExtraData root
  980. func (s *StateDB) Commit(deleteEmptyObjects bool) (common.Hash, error) {
  981. if s.dbErr != nil {
  982. return common.Hash{}, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
  983. }
  984. // Finalize any pending changes and merge everything into the tries
  985. s.IntermediateRoot(deleteEmptyObjects)
  986. s.mutex.Lock()
  987. // Commit objects to the trie, measuring the elapsed time
  988. codeWriter := s.db.TrieDB().DiskDB().NewBatch()
  989. for addr := range s.stateObjectsDirty {
  990. if obj := s.stateObjects[addr]; !obj.deleted {
  991. // Write any contract code associated with the state object
  992. if obj.code != nil && obj.dirtyCode {
  993. rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code)
  994. obj.dirtyCode = false
  995. }
  996. // Write any storage changes in the state object to its storage trie
  997. if err := obj.CommitTrie(s.db); err != nil {
  998. return common.Hash{}, err
  999. }
  1000. }
  1001. }
  1002. if len(s.stateObjectsDirty) > 0 {
  1003. s.stateObjectsDirty = make(map[common.Address]struct{})
  1004. }
  1005. s.mutex.Unlock()
  1006. if codeWriter.ValueSize() > 0 {
  1007. if err := codeWriter.Write(); err != nil {
  1008. log.Crit("Failed to commit dirty codes", "error", err)
  1009. }
  1010. }
  1011. // Write the account trie changes, measuing the amount of wasted time
  1012. var start time.Time
  1013. if metrics.EnabledExpensive {
  1014. start = time.Now()
  1015. }
  1016. // The onleaf func is called _serially_, so we can reuse the same account
  1017. // for unmarshalling every time.
  1018. var account Account
  1019. root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error {
  1020. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  1021. return nil
  1022. }
  1023. if account.Root != emptyRoot {
  1024. s.db.TrieDB().Reference(account.Root, parent)
  1025. }
  1026. return nil
  1027. })
  1028. if metrics.EnabledExpensive {
  1029. s.AccountCommits += time.Since(start)
  1030. }
  1031. // If snapshotting is enabled, update the snapshot tree with this new version
  1032. if s.snap != nil {
  1033. if metrics.EnabledExpensive {
  1034. defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
  1035. }
  1036. // Only update if there's a state transition (skip empty Clique blocks)
  1037. if parent := s.snap.Root(); parent != root {
  1038. if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage); err != nil {
  1039. log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
  1040. }
  1041. // Keep 128 diff layers in the memory, persistent layer is 129th.
  1042. // - head layer is paired with HEAD state
  1043. // - head-1 layer is paired with HEAD-1 state
  1044. // - head-127 layer(bottom-most diff layer) is paired with HEAD-127 state
  1045. if err := s.snaps.Cap(root, 128); err != nil {
  1046. log.Warn("Failed to cap snapshot tree", "root", root, "layers", 128, "err", err)
  1047. }
  1048. }
  1049. s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
  1050. }
  1051. // Quorum
  1052. // linking the state root and the AccountExtraData root
  1053. if err == nil {
  1054. // commit the AccountExtraData trie
  1055. extraDataRoot, err := s.accountExtraDataTrie.Commit(nil)
  1056. if err != nil {
  1057. return common.Hash{}, fmt.Errorf("unable to commit the AccountExtraData trie: %v", err)
  1058. }
  1059. log.Debug("AccountExtraData root after trie commit", "root", extraDataRoot)
  1060. // link the new state root to the AccountExtraData root
  1061. err = s.db.AccountExtraDataLinker().Link(root, extraDataRoot)
  1062. if err != nil {
  1063. return common.Hash{}, fmt.Errorf("Unable to link the state root to the privacy metadata root: %v", err)
  1064. }
  1065. // add a reference from the AccountExtraData root to the state root so that when the state root is written
  1066. // to the DB the the AccountExtraData root is also written
  1067. s.db.TrieDB().Reference(extraDataRoot, root)
  1068. }
  1069. return root, err
  1070. }
  1071. // PrepareAccessList handles the preparatory steps for executing a state transition with
  1072. // regards to both EIP-2929 and EIP-2930:
  1073. //
  1074. // - Add sender to access list (2929)
  1075. // - Add destination to access list (2929)
  1076. // - Add precompiles to access list (2929)
  1077. // - Add the contents of the optional tx access list (2930)
  1078. //
  1079. // This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.
  1080. func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
  1081. s.AddAddressToAccessList(sender)
  1082. if dst != nil {
  1083. s.AddAddressToAccessList(*dst)
  1084. // If it's a create-tx, the destination will be added inside evm.create
  1085. }
  1086. for _, addr := range precompiles {
  1087. s.AddAddressToAccessList(addr)
  1088. }
  1089. for _, el := range list {
  1090. s.AddAddressToAccessList(el.Address)
  1091. for _, key := range el.StorageKeys {
  1092. s.AddSlotToAccessList(el.Address, key)
  1093. }
  1094. }
  1095. }
  1096. // AddAddressToAccessList adds the given address to the access list
  1097. func (s *StateDB) AddAddressToAccessList(addr common.Address) {
  1098. if s.accessList.AddAddress(addr) {
  1099. s.journal.append(accessListAddAccountChange{&addr})
  1100. }
  1101. }
  1102. // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
  1103. func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
  1104. addrMod, slotMod := s.accessList.AddSlot(addr, slot)
  1105. if addrMod {
  1106. // In practice, this should not happen, since there is no way to enter the
  1107. // scope of 'address' without having the 'address' become already added
  1108. // to the access list (via call-variant, create, etc).
  1109. // Better safe than sorry, though
  1110. s.journal.append(accessListAddAccountChange{&addr})
  1111. }
  1112. if slotMod {
  1113. s.journal.append(accessListAddSlotChange{
  1114. address: &addr,
  1115. slot: &slot,
  1116. })
  1117. }
  1118. }
  1119. // AddressInAccessList returns true if the given address is in the access list.
  1120. func (s *StateDB) AddressInAccessList(addr common.Address) bool {
  1121. return s.accessList.ContainsAddress(addr)
  1122. }
  1123. // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
  1124. func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
  1125. return s.accessList.Contains(addr, slot)
  1126. }