statedb.go 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. "runtime"
  23. "sort"
  24. "sync"
  25. "time"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/common/gopool"
  28. "github.com/ethereum/go-ethereum/core/rawdb"
  29. "github.com/ethereum/go-ethereum/core/state/snapshot"
  30. "github.com/ethereum/go-ethereum/core/types"
  31. "github.com/ethereum/go-ethereum/crypto"
  32. "github.com/ethereum/go-ethereum/ethdb"
  33. "github.com/ethereum/go-ethereum/log"
  34. "github.com/ethereum/go-ethereum/metrics"
  35. "github.com/ethereum/go-ethereum/rlp"
  36. "github.com/ethereum/go-ethereum/trie"
  37. )
  38. const (
  39. preLoadLimit = 128
  40. defaultNumOfSlots = 100
  41. )
  42. type revision struct {
  43. id int
  44. journalIndex int
  45. }
  46. var (
  47. // emptyRoot is the known root hash of an empty trie.
  48. emptyRoot = common.HexToHash("56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421")
  49. emptyAddr = crypto.Keccak256Hash(common.Address{}.Bytes())
  50. )
  51. type proofList [][]byte
  52. func (n *proofList) Put(key []byte, value []byte) error {
  53. *n = append(*n, value)
  54. return nil
  55. }
  56. func (n *proofList) Delete(key []byte) error {
  57. panic("not supported")
  58. }
  59. // StateDB structs within the ethereum protocol are used to store anything
  60. // within the merkle trie. StateDBs take care of caching and storing
  61. // nested states. It's the general query interface to retrieve:
  62. // * Contracts
  63. // * Accounts
  64. type StateDB struct {
  65. db Database
  66. prefetcherLock sync.Mutex
  67. prefetcher *triePrefetcher
  68. originalRoot common.Hash // The pre-state root, before any changes were made
  69. expectedRoot common.Hash // The state root in the block header
  70. stateRoot common.Hash // The calculation result of IntermediateRoot
  71. trie Trie
  72. hasher crypto.KeccakState
  73. diffLayer *types.DiffLayer
  74. diffTries map[common.Address]Trie
  75. diffCode map[common.Hash][]byte
  76. lightProcessed bool
  77. fullProcessed bool
  78. pipeCommit bool
  79. snapMux sync.Mutex
  80. snaps *snapshot.Tree
  81. snap snapshot.Snapshot
  82. snapDestructs map[common.Address]struct{}
  83. snapAccounts map[common.Address][]byte
  84. snapStorage map[common.Address]map[string][]byte
  85. // This map holds 'live' objects, which will get modified while processing a state transition.
  86. stateObjects map[common.Address]*StateObject
  87. stateObjectsPending map[common.Address]struct{} // State objects finalized but not yet written to the trie
  88. stateObjectsDirty map[common.Address]struct{} // State objects modified in the current execution
  89. // DB error.
  90. // State objects are used by the consensus core and VM which are
  91. // unable to deal with database-level errors. Any error that occurs
  92. // during a database read is memoized here and will eventually be returned
  93. // by StateDB.Commit.
  94. dbErr error
  95. // The refund counter, also used by state transitioning.
  96. refund uint64
  97. thash, bhash common.Hash
  98. txIndex int
  99. logs map[common.Hash][]*types.Log
  100. logSize uint
  101. preimages map[common.Hash][]byte
  102. // Per-transaction access list
  103. accessList *accessList
  104. // Journal of state modifications. This is the backbone of
  105. // Snapshot and RevertToSnapshot.
  106. journal *journal
  107. validRevisions []revision
  108. nextRevisionId int
  109. // Measurements gathered during execution for debugging purposes
  110. MetricsMux sync.Mutex
  111. AccountReads time.Duration
  112. AccountHashes time.Duration
  113. AccountUpdates time.Duration
  114. AccountCommits time.Duration
  115. StorageReads time.Duration
  116. StorageHashes time.Duration
  117. StorageUpdates time.Duration
  118. StorageCommits time.Duration
  119. SnapshotAccountReads time.Duration
  120. SnapshotStorageReads time.Duration
  121. SnapshotCommits time.Duration
  122. }
  123. // New creates a new state from a given trie.
  124. func New(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
  125. return newStateDB(root, db, snaps)
  126. }
  127. func newStateDB(root common.Hash, db Database, snaps *snapshot.Tree) (*StateDB, error) {
  128. sdb := &StateDB{
  129. db: db,
  130. originalRoot: root,
  131. snaps: snaps,
  132. stateObjects: make(map[common.Address]*StateObject, defaultNumOfSlots),
  133. stateObjectsPending: make(map[common.Address]struct{}, defaultNumOfSlots),
  134. stateObjectsDirty: make(map[common.Address]struct{}, defaultNumOfSlots),
  135. logs: make(map[common.Hash][]*types.Log, defaultNumOfSlots),
  136. preimages: make(map[common.Hash][]byte),
  137. journal: newJournal(),
  138. hasher: crypto.NewKeccakState(),
  139. }
  140. if sdb.snaps != nil {
  141. if sdb.snap = sdb.snaps.Snapshot(root); sdb.snap != nil {
  142. sdb.snapDestructs = make(map[common.Address]struct{})
  143. sdb.snapAccounts = make(map[common.Address][]byte)
  144. sdb.snapStorage = make(map[common.Address]map[string][]byte)
  145. }
  146. }
  147. snapVerified := sdb.snap != nil && sdb.snap.Verified()
  148. tr, err := db.OpenTrie(root)
  149. // return error when 1. failed to open trie and 2. the snap is nil or the snap is not nil and done verification
  150. if err != nil && (sdb.snap == nil || snapVerified) {
  151. return nil, err
  152. }
  153. sdb.trie = tr
  154. return sdb, nil
  155. }
  156. // StartPrefetcher initializes a new trie prefetcher to pull in nodes from the
  157. // state trie concurrently while the state is mutated so that when we reach the
  158. // commit phase, most of the needed data is already hot.
  159. func (s *StateDB) StartPrefetcher(namespace string) {
  160. s.prefetcherLock.Lock()
  161. defer s.prefetcherLock.Unlock()
  162. if s.prefetcher != nil {
  163. s.prefetcher.close()
  164. s.prefetcher = nil
  165. }
  166. if s.snap != nil {
  167. s.prefetcher = newTriePrefetcher(s.db, s.originalRoot, namespace)
  168. }
  169. }
  170. // StopPrefetcher terminates a running prefetcher and reports any leftover stats
  171. // from the gathered metrics.
  172. func (s *StateDB) StopPrefetcher() {
  173. s.prefetcherLock.Lock()
  174. defer s.prefetcherLock.Unlock()
  175. if s.prefetcher != nil {
  176. s.prefetcher.close()
  177. s.prefetcher = nil
  178. }
  179. }
  180. // Mark that the block is processed by diff layer
  181. func (s *StateDB) SetExpectedStateRoot(root common.Hash) {
  182. s.expectedRoot = root
  183. }
  184. // Mark that the block is processed by diff layer
  185. func (s *StateDB) MarkLightProcessed() {
  186. s.lightProcessed = true
  187. }
  188. // Enable the pipeline commit function of statedb
  189. func (s *StateDB) EnablePipeCommit() {
  190. if s.snap != nil {
  191. s.pipeCommit = true
  192. }
  193. }
  194. // Mark that the block is full processed
  195. func (s *StateDB) MarkFullProcessed() {
  196. s.fullProcessed = true
  197. }
  198. func (s *StateDB) IsLightProcessed() bool {
  199. return s.lightProcessed
  200. }
  201. // setError remembers the first non-nil error it is called with.
  202. func (s *StateDB) setError(err error) {
  203. if s.dbErr == nil {
  204. s.dbErr = err
  205. }
  206. }
  207. func (s *StateDB) Error() error {
  208. return s.dbErr
  209. }
  210. // Not thread safe
  211. func (s *StateDB) Trie() (Trie, error) {
  212. if s.trie == nil {
  213. err := s.WaitPipeVerification()
  214. if err != nil {
  215. return nil, err
  216. }
  217. tr, err := s.db.OpenTrie(s.originalRoot)
  218. if err != nil {
  219. return nil, err
  220. }
  221. s.trie = tr
  222. }
  223. return s.trie, nil
  224. }
  225. func (s *StateDB) SetDiff(diffLayer *types.DiffLayer, diffTries map[common.Address]Trie, diffCode map[common.Hash][]byte) {
  226. s.diffLayer, s.diffTries, s.diffCode = diffLayer, diffTries, diffCode
  227. }
  228. func (s *StateDB) SetSnapData(snapDestructs map[common.Address]struct{}, snapAccounts map[common.Address][]byte,
  229. snapStorage map[common.Address]map[string][]byte) {
  230. s.snapDestructs, s.snapAccounts, s.snapStorage = snapDestructs, snapAccounts, snapStorage
  231. }
  232. func (s *StateDB) AddLog(log *types.Log) {
  233. s.journal.append(addLogChange{txhash: s.thash})
  234. log.TxHash = s.thash
  235. log.BlockHash = s.bhash
  236. log.TxIndex = uint(s.txIndex)
  237. log.Index = s.logSize
  238. s.logs[s.thash] = append(s.logs[s.thash], log)
  239. s.logSize++
  240. }
  241. func (s *StateDB) GetLogs(hash common.Hash) []*types.Log {
  242. return s.logs[hash]
  243. }
  244. func (s *StateDB) Logs() []*types.Log {
  245. var logs []*types.Log
  246. for _, lgs := range s.logs {
  247. logs = append(logs, lgs...)
  248. }
  249. return logs
  250. }
  251. // AddPreimage records a SHA3 preimage seen by the VM.
  252. func (s *StateDB) AddPreimage(hash common.Hash, preimage []byte) {
  253. if _, ok := s.preimages[hash]; !ok {
  254. s.journal.append(addPreimageChange{hash: hash})
  255. pi := make([]byte, len(preimage))
  256. copy(pi, preimage)
  257. s.preimages[hash] = pi
  258. }
  259. }
  260. // Preimages returns a list of SHA3 preimages that have been submitted.
  261. func (s *StateDB) Preimages() map[common.Hash][]byte {
  262. return s.preimages
  263. }
  264. // AddRefund adds gas to the refund counter
  265. func (s *StateDB) AddRefund(gas uint64) {
  266. s.journal.append(refundChange{prev: s.refund})
  267. s.refund += gas
  268. }
  269. // SubRefund removes gas from the refund counter.
  270. // This method will panic if the refund counter goes below zero
  271. func (s *StateDB) SubRefund(gas uint64) {
  272. s.journal.append(refundChange{prev: s.refund})
  273. if gas > s.refund {
  274. panic(fmt.Sprintf("Refund counter below zero (gas: %d > refund: %d)", gas, s.refund))
  275. }
  276. s.refund -= gas
  277. }
  278. // Exist reports whether the given account address exists in the state.
  279. // Notably this also returns true for suicided accounts.
  280. func (s *StateDB) Exist(addr common.Address) bool {
  281. return s.getStateObject(addr) != nil
  282. }
  283. // Empty returns whether the state object is either non-existent
  284. // or empty according to the EIP161 specification (balance = nonce = code = 0)
  285. func (s *StateDB) Empty(addr common.Address) bool {
  286. so := s.getStateObject(addr)
  287. return so == nil || so.empty()
  288. }
  289. // GetBalance retrieves the balance from the given address or 0 if object not found
  290. func (s *StateDB) GetBalance(addr common.Address) *big.Int {
  291. stateObject := s.getStateObject(addr)
  292. if stateObject != nil {
  293. return stateObject.Balance()
  294. }
  295. return common.Big0
  296. }
  297. func (s *StateDB) GetNonce(addr common.Address) uint64 {
  298. stateObject := s.getStateObject(addr)
  299. if stateObject != nil {
  300. return stateObject.Nonce()
  301. }
  302. return 0
  303. }
  304. // TxIndex returns the current transaction index set by Prepare.
  305. func (s *StateDB) TxIndex() int {
  306. return s.txIndex
  307. }
  308. // BlockHash returns the current block hash set by Prepare.
  309. func (s *StateDB) BlockHash() common.Hash {
  310. return s.bhash
  311. }
  312. func (s *StateDB) GetCode(addr common.Address) []byte {
  313. stateObject := s.getStateObject(addr)
  314. if stateObject != nil {
  315. return stateObject.Code(s.db)
  316. }
  317. return nil
  318. }
  319. func (s *StateDB) GetCodeSize(addr common.Address) int {
  320. stateObject := s.getStateObject(addr)
  321. if stateObject != nil {
  322. return stateObject.CodeSize(s.db)
  323. }
  324. return 0
  325. }
  326. func (s *StateDB) GetCodeHash(addr common.Address) common.Hash {
  327. stateObject := s.getStateObject(addr)
  328. if stateObject == nil {
  329. return common.Hash{}
  330. }
  331. return common.BytesToHash(stateObject.CodeHash())
  332. }
  333. // GetState retrieves a value from the given account's storage trie.
  334. func (s *StateDB) GetState(addr common.Address, hash common.Hash) common.Hash {
  335. stateObject := s.getStateObject(addr)
  336. if stateObject != nil {
  337. return stateObject.GetState(s.db, hash)
  338. }
  339. return common.Hash{}
  340. }
  341. // GetProof returns the Merkle proof for a given account.
  342. func (s *StateDB) GetProof(addr common.Address) ([][]byte, error) {
  343. return s.GetProofByHash(crypto.Keccak256Hash(addr.Bytes()))
  344. }
  345. // GetProofByHash returns the Merkle proof for a given account.
  346. func (s *StateDB) GetProofByHash(addrHash common.Hash) ([][]byte, error) {
  347. var proof proofList
  348. if _, err := s.Trie(); err != nil {
  349. return nil, err
  350. }
  351. err := s.trie.Prove(addrHash[:], 0, &proof)
  352. return proof, err
  353. }
  354. // GetStorageProof returns the Merkle proof for given storage slot.
  355. func (s *StateDB) GetStorageProof(a common.Address, key common.Hash) ([][]byte, error) {
  356. var proof proofList
  357. trie := s.StorageTrie(a)
  358. if trie == nil {
  359. return proof, errors.New("storage trie for requested address does not exist")
  360. }
  361. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  362. return proof, err
  363. }
  364. // GetStorageProofByHash returns the Merkle proof for given storage slot.
  365. func (s *StateDB) GetStorageProofByHash(a common.Address, key common.Hash) ([][]byte, error) {
  366. var proof proofList
  367. trie := s.StorageTrie(a)
  368. if trie == nil {
  369. return proof, errors.New("storage trie for requested address does not exist")
  370. }
  371. err := trie.Prove(crypto.Keccak256(key.Bytes()), 0, &proof)
  372. return proof, err
  373. }
  374. // GetCommittedState retrieves a value from the given account's committed storage trie.
  375. func (s *StateDB) GetCommittedState(addr common.Address, hash common.Hash) common.Hash {
  376. stateObject := s.getStateObject(addr)
  377. if stateObject != nil {
  378. return stateObject.GetCommittedState(s.db, hash)
  379. }
  380. return common.Hash{}
  381. }
  382. // Database retrieves the low level database supporting the lower level trie ops.
  383. func (s *StateDB) Database() Database {
  384. return s.db
  385. }
  386. // StorageTrie returns the storage trie of an account.
  387. // The return value is a copy and is nil for non-existent accounts.
  388. func (s *StateDB) StorageTrie(addr common.Address) Trie {
  389. stateObject := s.getStateObject(addr)
  390. if stateObject == nil {
  391. return nil
  392. }
  393. cpy := stateObject.deepCopy(s)
  394. cpy.updateTrie(s.db)
  395. return cpy.getTrie(s.db)
  396. }
  397. func (s *StateDB) HasSuicided(addr common.Address) bool {
  398. stateObject := s.getStateObject(addr)
  399. if stateObject != nil {
  400. return stateObject.suicided
  401. }
  402. return false
  403. }
  404. /*
  405. * SETTERS
  406. */
  407. // AddBalance adds amount to the account associated with addr.
  408. func (s *StateDB) AddBalance(addr common.Address, amount *big.Int) {
  409. stateObject := s.GetOrNewStateObject(addr)
  410. if stateObject != nil {
  411. stateObject.AddBalance(amount)
  412. }
  413. }
  414. // SubBalance subtracts amount from the account associated with addr.
  415. func (s *StateDB) SubBalance(addr common.Address, amount *big.Int) {
  416. stateObject := s.GetOrNewStateObject(addr)
  417. if stateObject != nil {
  418. stateObject.SubBalance(amount)
  419. }
  420. }
  421. func (s *StateDB) SetBalance(addr common.Address, amount *big.Int) {
  422. stateObject := s.GetOrNewStateObject(addr)
  423. if stateObject != nil {
  424. stateObject.SetBalance(amount)
  425. }
  426. }
  427. func (s *StateDB) SetNonce(addr common.Address, nonce uint64) {
  428. stateObject := s.GetOrNewStateObject(addr)
  429. if stateObject != nil {
  430. stateObject.SetNonce(nonce)
  431. }
  432. }
  433. func (s *StateDB) SetCode(addr common.Address, code []byte) {
  434. stateObject := s.GetOrNewStateObject(addr)
  435. if stateObject != nil {
  436. stateObject.SetCode(crypto.Keccak256Hash(code), code)
  437. }
  438. }
  439. func (s *StateDB) SetState(addr common.Address, key, value common.Hash) {
  440. stateObject := s.GetOrNewStateObject(addr)
  441. if stateObject != nil {
  442. stateObject.SetState(s.db, key, value)
  443. }
  444. }
  445. // SetStorage replaces the entire storage for the specified account with given
  446. // storage. This function should only be used for debugging.
  447. func (s *StateDB) SetStorage(addr common.Address, storage map[common.Hash]common.Hash) {
  448. stateObject := s.GetOrNewStateObject(addr)
  449. if stateObject != nil {
  450. stateObject.SetStorage(storage)
  451. }
  452. }
  453. // Suicide marks the given account as suicided.
  454. // This clears the account balance.
  455. //
  456. // The account's state object is still available until the state is committed,
  457. // getStateObject will return a non-nil account after Suicide.
  458. func (s *StateDB) Suicide(addr common.Address) bool {
  459. stateObject := s.getStateObject(addr)
  460. if stateObject == nil {
  461. return false
  462. }
  463. s.journal.append(suicideChange{
  464. account: &addr,
  465. prev: stateObject.suicided,
  466. prevbalance: new(big.Int).Set(stateObject.Balance()),
  467. })
  468. stateObject.markSuicided()
  469. stateObject.data.Balance = new(big.Int)
  470. return true
  471. }
  472. //
  473. // Setting, updating & deleting state object methods.
  474. //
  475. // updateStateObject writes the given object to the trie.
  476. func (s *StateDB) updateStateObject(obj *StateObject) {
  477. // Track the amount of time wasted on updating the account from the trie
  478. if metrics.EnabledExpensive {
  479. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  480. }
  481. // Encode the account and update the account trie
  482. addr := obj.Address()
  483. data := obj.encodeData
  484. var err error
  485. if data == nil {
  486. data, err = rlp.EncodeToBytes(obj)
  487. if err != nil {
  488. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  489. }
  490. }
  491. if err = s.trie.TryUpdate(addr[:], data); err != nil {
  492. s.setError(fmt.Errorf("updateStateObject (%x) error: %v", addr[:], err))
  493. }
  494. }
  495. // deleteStateObject removes the given object from the state trie.
  496. func (s *StateDB) deleteStateObject(obj *StateObject) {
  497. // Track the amount of time wasted on deleting the account from the trie
  498. if metrics.EnabledExpensive {
  499. defer func(start time.Time) { s.AccountUpdates += time.Since(start) }(time.Now())
  500. }
  501. // Delete the account from the trie
  502. addr := obj.Address()
  503. if err := s.trie.TryDelete(addr[:]); err != nil {
  504. s.setError(fmt.Errorf("deleteStateObject (%x) error: %v", addr[:], err))
  505. }
  506. }
  507. // getStateObject retrieves a state object given by the address, returning nil if
  508. // the object is not found or was deleted in this execution context. If you need
  509. // to differentiate between non-existent/just-deleted, use getDeletedStateObject.
  510. func (s *StateDB) getStateObject(addr common.Address) *StateObject {
  511. if obj := s.getDeletedStateObject(addr); obj != nil && !obj.deleted {
  512. return obj
  513. }
  514. return nil
  515. }
  516. func (s *StateDB) TryPreload(block *types.Block, signer types.Signer) {
  517. accounts := make(map[common.Address]bool, block.Transactions().Len())
  518. accountsSlice := make([]common.Address, 0, block.Transactions().Len())
  519. for _, tx := range block.Transactions() {
  520. from, err := types.Sender(signer, tx)
  521. if err != nil {
  522. break
  523. }
  524. accounts[from] = true
  525. if tx.To() != nil {
  526. accounts[*tx.To()] = true
  527. }
  528. }
  529. for account := range accounts {
  530. accountsSlice = append(accountsSlice, account)
  531. }
  532. if len(accountsSlice) >= preLoadLimit && len(accountsSlice) > runtime.NumCPU() {
  533. objsChan := make(chan []*StateObject, runtime.NumCPU())
  534. for i := 0; i < runtime.NumCPU(); i++ {
  535. start := i * len(accountsSlice) / runtime.NumCPU()
  536. end := (i + 1) * len(accountsSlice) / runtime.NumCPU()
  537. if i+1 == runtime.NumCPU() {
  538. end = len(accountsSlice)
  539. }
  540. go func(start, end int) {
  541. objs := s.preloadStateObject(accountsSlice[start:end])
  542. objsChan <- objs
  543. }(start, end)
  544. }
  545. for i := 0; i < runtime.NumCPU(); i++ {
  546. objs := <-objsChan
  547. for _, obj := range objs {
  548. s.SetStateObject(obj)
  549. }
  550. }
  551. }
  552. }
  553. func (s *StateDB) preloadStateObject(address []common.Address) []*StateObject {
  554. // Prefer live objects if any is available
  555. if s.snap == nil {
  556. return nil
  557. }
  558. hasher := crypto.NewKeccakState()
  559. objs := make([]*StateObject, 0, len(address))
  560. for _, addr := range address {
  561. // If no live objects are available, attempt to use snapshots
  562. if acc, err := s.snap.Account(crypto.HashData(hasher, addr.Bytes())); err == nil {
  563. if acc == nil {
  564. continue
  565. }
  566. data := &Account{
  567. Nonce: acc.Nonce,
  568. Balance: acc.Balance,
  569. CodeHash: acc.CodeHash,
  570. Root: common.BytesToHash(acc.Root),
  571. }
  572. if len(data.CodeHash) == 0 {
  573. data.CodeHash = emptyCodeHash
  574. }
  575. if data.Root == (common.Hash{}) {
  576. data.Root = emptyRoot
  577. }
  578. // Insert into the live set
  579. obj := newObject(s, addr, *data)
  580. objs = append(objs, obj)
  581. }
  582. // Do not enable this feature when snapshot is not enabled.
  583. }
  584. return objs
  585. }
  586. // getDeletedStateObject is similar to getStateObject, but instead of returning
  587. // nil for a deleted state object, it returns the actual object with the deleted
  588. // flag set. This is needed by the state journal to revert to the correct s-
  589. // destructed object instead of wiping all knowledge about the state object.
  590. func (s *StateDB) getDeletedStateObject(addr common.Address) *StateObject {
  591. // Prefer live objects if any is available
  592. if obj := s.stateObjects[addr]; obj != nil {
  593. return obj
  594. }
  595. // If no live objects are available, attempt to use snapshots
  596. var (
  597. data *Account
  598. err error
  599. )
  600. if s.snap != nil {
  601. if metrics.EnabledExpensive {
  602. defer func(start time.Time) { s.SnapshotAccountReads += time.Since(start) }(time.Now())
  603. }
  604. var acc *snapshot.Account
  605. if acc, err = s.snap.Account(crypto.HashData(s.hasher, addr.Bytes())); err == nil {
  606. if acc == nil {
  607. return nil
  608. }
  609. data = &Account{
  610. Nonce: acc.Nonce,
  611. Balance: acc.Balance,
  612. CodeHash: acc.CodeHash,
  613. Root: common.BytesToHash(acc.Root),
  614. }
  615. if len(data.CodeHash) == 0 {
  616. data.CodeHash = emptyCodeHash
  617. }
  618. if data.Root == (common.Hash{}) {
  619. data.Root = emptyRoot
  620. }
  621. }
  622. }
  623. // If snapshot unavailable or reading from it failed, load from the database
  624. if s.snap == nil || err != nil {
  625. if s.trie == nil {
  626. tr, err := s.db.OpenTrie(s.originalRoot)
  627. if err != nil {
  628. s.setError(fmt.Errorf("failed to open trie tree"))
  629. return nil
  630. }
  631. s.trie = tr
  632. }
  633. if metrics.EnabledExpensive {
  634. defer func(start time.Time) { s.AccountReads += time.Since(start) }(time.Now())
  635. }
  636. enc, err := s.trie.TryGet(addr.Bytes())
  637. if err != nil {
  638. s.setError(fmt.Errorf("getDeleteStateObject (%x) error: %v", addr.Bytes(), err))
  639. return nil
  640. }
  641. if len(enc) == 0 {
  642. return nil
  643. }
  644. data = new(Account)
  645. if err := rlp.DecodeBytes(enc, data); err != nil {
  646. log.Error("Failed to decode state object", "addr", addr, "err", err)
  647. return nil
  648. }
  649. }
  650. // Insert into the live set
  651. obj := newObject(s, addr, *data)
  652. s.SetStateObject(obj)
  653. return obj
  654. }
  655. func (s *StateDB) SetStateObject(object *StateObject) {
  656. s.stateObjects[object.Address()] = object
  657. }
  658. // GetOrNewStateObject retrieves a state object or create a new state object if nil.
  659. func (s *StateDB) GetOrNewStateObject(addr common.Address) *StateObject {
  660. stateObject := s.getStateObject(addr)
  661. if stateObject == nil {
  662. stateObject, _ = s.createObject(addr)
  663. }
  664. return stateObject
  665. }
  666. // createObject creates a new state object. If there is an existing account with
  667. // the given address, it is overwritten and returned as the second return value.
  668. func (s *StateDB) createObject(addr common.Address) (newobj, prev *StateObject) {
  669. prev = s.getDeletedStateObject(addr) // Note, prev might have been deleted, we need that!
  670. var prevdestruct bool
  671. if s.snap != nil && prev != nil {
  672. _, prevdestruct = s.snapDestructs[prev.address]
  673. if !prevdestruct {
  674. s.snapDestructs[prev.address] = struct{}{}
  675. }
  676. }
  677. newobj = newObject(s, addr, Account{})
  678. newobj.setNonce(0) // sets the object to dirty
  679. if prev == nil {
  680. s.journal.append(createObjectChange{account: &addr})
  681. } else {
  682. s.journal.append(resetObjectChange{prev: prev, prevdestruct: prevdestruct})
  683. }
  684. s.SetStateObject(newobj)
  685. if prev != nil && !prev.deleted {
  686. return newobj, prev
  687. }
  688. return newobj, nil
  689. }
  690. // CreateAccount explicitly creates a state object. If a state object with the address
  691. // already exists the balance is carried over to the new account.
  692. //
  693. // CreateAccount is called during the EVM CREATE operation. The situation might arise that
  694. // a contract does the following:
  695. //
  696. // 1. sends funds to sha(account ++ (nonce + 1))
  697. // 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
  698. //
  699. // Carrying over the balance ensures that Ether doesn't disappear.
  700. func (s *StateDB) CreateAccount(addr common.Address) {
  701. newObj, prev := s.createObject(addr)
  702. if prev != nil {
  703. newObj.setBalance(prev.data.Balance)
  704. }
  705. }
  706. func (db *StateDB) ForEachStorage(addr common.Address, cb func(key, value common.Hash) bool) error {
  707. so := db.getStateObject(addr)
  708. if so == nil {
  709. return nil
  710. }
  711. it := trie.NewIterator(so.getTrie(db.db).NodeIterator(nil))
  712. for it.Next() {
  713. key := common.BytesToHash(db.trie.GetKey(it.Key))
  714. if value, dirty := so.dirtyStorage[key]; dirty {
  715. if !cb(key, value) {
  716. return nil
  717. }
  718. continue
  719. }
  720. if len(it.Value) > 0 {
  721. _, content, _, err := rlp.Split(it.Value)
  722. if err != nil {
  723. return err
  724. }
  725. if !cb(key, common.BytesToHash(content)) {
  726. return nil
  727. }
  728. }
  729. }
  730. return nil
  731. }
  732. // Copy creates a deep, independent copy of the state.
  733. // Snapshots of the copied state cannot be applied to the copy.
  734. func (s *StateDB) Copy() *StateDB {
  735. // Copy all the basic fields, initialize the memory ones
  736. state := &StateDB{
  737. db: s.db,
  738. trie: s.db.CopyTrie(s.trie),
  739. stateObjects: make(map[common.Address]*StateObject, len(s.journal.dirties)),
  740. stateObjectsPending: make(map[common.Address]struct{}, len(s.stateObjectsPending)),
  741. stateObjectsDirty: make(map[common.Address]struct{}, len(s.journal.dirties)),
  742. refund: s.refund,
  743. logs: make(map[common.Hash][]*types.Log, len(s.logs)),
  744. logSize: s.logSize,
  745. preimages: make(map[common.Hash][]byte, len(s.preimages)),
  746. journal: newJournal(),
  747. hasher: crypto.NewKeccakState(),
  748. }
  749. // Copy the dirty states, logs, and preimages
  750. for addr := range s.journal.dirties {
  751. // As documented [here](https://github.com/ethereum/go-ethereum/pull/16485#issuecomment-380438527),
  752. // and in the Finalise-method, there is a case where an object is in the journal but not
  753. // in the stateObjects: OOG after touch on ripeMD prior to Byzantium. Thus, we need to check for
  754. // nil
  755. if object, exist := s.stateObjects[addr]; exist {
  756. // Even though the original object is dirty, we are not copying the journal,
  757. // so we need to make sure that anyside effect the journal would have caused
  758. // during a commit (or similar op) is already applied to the copy.
  759. state.stateObjects[addr] = object.deepCopy(state)
  760. state.stateObjectsDirty[addr] = struct{}{} // Mark the copy dirty to force internal (code/state) commits
  761. state.stateObjectsPending[addr] = struct{}{} // Mark the copy pending to force external (account) commits
  762. }
  763. }
  764. // Above, we don't copy the actual journal. This means that if the copy is copied, the
  765. // loop above will be a no-op, since the copy's journal is empty.
  766. // Thus, here we iterate over stateObjects, to enable copies of copies
  767. for addr := range s.stateObjectsPending {
  768. if _, exist := state.stateObjects[addr]; !exist {
  769. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  770. }
  771. state.stateObjectsPending[addr] = struct{}{}
  772. }
  773. for addr := range s.stateObjectsDirty {
  774. if _, exist := state.stateObjects[addr]; !exist {
  775. state.stateObjects[addr] = s.stateObjects[addr].deepCopy(state)
  776. }
  777. state.stateObjectsDirty[addr] = struct{}{}
  778. }
  779. for hash, logs := range s.logs {
  780. cpy := make([]*types.Log, len(logs))
  781. for i, l := range logs {
  782. cpy[i] = new(types.Log)
  783. *cpy[i] = *l
  784. }
  785. state.logs[hash] = cpy
  786. }
  787. for hash, preimage := range s.preimages {
  788. state.preimages[hash] = preimage
  789. }
  790. // Do we need to copy the access list? In practice: No. At the start of a
  791. // transaction, the access list is empty. In practice, we only ever copy state
  792. // _between_ transactions/blocks, never in the middle of a transaction.
  793. // However, it doesn't cost us much to copy an empty list, so we do it anyway
  794. // to not blow up if we ever decide copy it in the middle of a transaction
  795. if s.accessList != nil {
  796. state.accessList = s.accessList.Copy()
  797. }
  798. // If there's a prefetcher running, make an inactive copy of it that can
  799. // only access data but does not actively preload (since the user will not
  800. // know that they need to explicitly terminate an active copy).
  801. if s.prefetcher != nil {
  802. state.prefetcher = s.prefetcher.copy()
  803. }
  804. if s.snaps != nil {
  805. // In order for the miner to be able to use and make additions
  806. // to the snapshot tree, we need to copy that aswell.
  807. // Otherwise, any block mined by ourselves will cause gaps in the tree,
  808. // and force the miner to operate trie-backed only
  809. state.snaps = s.snaps
  810. state.snap = s.snap
  811. // deep copy needed
  812. state.snapDestructs = make(map[common.Address]struct{})
  813. for k, v := range s.snapDestructs {
  814. state.snapDestructs[k] = v
  815. }
  816. state.snapAccounts = make(map[common.Address][]byte)
  817. for k, v := range s.snapAccounts {
  818. state.snapAccounts[k] = v
  819. }
  820. state.snapStorage = make(map[common.Address]map[string][]byte)
  821. for k, v := range s.snapStorage {
  822. temp := make(map[string][]byte)
  823. for kk, vv := range v {
  824. temp[kk] = vv
  825. }
  826. state.snapStorage[k] = temp
  827. }
  828. }
  829. return state
  830. }
  831. // Snapshot returns an identifier for the current revision of the state.
  832. func (s *StateDB) Snapshot() int {
  833. id := s.nextRevisionId
  834. s.nextRevisionId++
  835. s.validRevisions = append(s.validRevisions, revision{id, s.journal.length()})
  836. return id
  837. }
  838. // RevertToSnapshot reverts all state changes made since the given revision.
  839. func (s *StateDB) RevertToSnapshot(revid int) {
  840. // Find the snapshot in the stack of valid snapshots.
  841. idx := sort.Search(len(s.validRevisions), func(i int) bool {
  842. return s.validRevisions[i].id >= revid
  843. })
  844. if idx == len(s.validRevisions) || s.validRevisions[idx].id != revid {
  845. panic(fmt.Errorf("revision id %v cannot be reverted", revid))
  846. }
  847. snapshot := s.validRevisions[idx].journalIndex
  848. // Replay the journal to undo changes and remove invalidated snapshots
  849. s.journal.revert(s, snapshot)
  850. s.validRevisions = s.validRevisions[:idx]
  851. }
  852. // GetRefund returns the current value of the refund counter.
  853. func (s *StateDB) GetRefund() uint64 {
  854. return s.refund
  855. }
  856. // GetRefund returns the current value of the refund counter.
  857. func (s *StateDB) WaitPipeVerification() error {
  858. // We need wait for the parent trie to commit
  859. if s.snap != nil {
  860. if valid := s.snap.WaitAndGetVerifyRes(); !valid {
  861. return fmt.Errorf("verification on parent snap failed")
  862. }
  863. }
  864. return nil
  865. }
  866. // Finalise finalises the state by removing the s destructed objects and clears
  867. // the journal as well as the refunds. Finalise, however, will not push any updates
  868. // into the tries just yet. Only IntermediateRoot or Commit will do that.
  869. func (s *StateDB) Finalise(deleteEmptyObjects bool) {
  870. addressesToPrefetch := make([][]byte, 0, len(s.journal.dirties))
  871. for addr := range s.journal.dirties {
  872. obj, exist := s.stateObjects[addr]
  873. if !exist {
  874. // ripeMD is 'touched' at block 1714175, in tx 0x1237f737031e40bcde4a8b7e717b2d15e3ecadfe49bb1bbc71ee9deb09c6fcf2
  875. // That tx goes out of gas, and although the notion of 'touched' does not exist there, the
  876. // touch-event will still be recorded in the journal. Since ripeMD is a special snowflake,
  877. // it will persist in the journal even though the journal is reverted. In this special circumstance,
  878. // it may exist in `s.journal.dirties` but not in `s.stateObjects`.
  879. // Thus, we can safely ignore it here
  880. continue
  881. }
  882. if obj.suicided || (deleteEmptyObjects && obj.empty()) {
  883. obj.deleted = true
  884. // If state snapshotting is active, also mark the destruction there.
  885. // Note, we can't do this only at the end of a block because multiple
  886. // transactions within the same block might self destruct and then
  887. // ressurrect an account; but the snapshotter needs both events.
  888. if s.snap != nil {
  889. s.snapDestructs[obj.address] = struct{}{} // We need to maintain account deletions explicitly (will remain set indefinitely)
  890. delete(s.snapAccounts, obj.address) // Clear out any previously updated account data (may be recreated via a ressurrect)
  891. delete(s.snapStorage, obj.address) // Clear out any previously updated storage data (may be recreated via a ressurrect)
  892. }
  893. } else {
  894. obj.finalise(true) // Prefetch slots in the background
  895. }
  896. if _, exist := s.stateObjectsPending[addr]; !exist {
  897. s.stateObjectsPending[addr] = struct{}{}
  898. }
  899. if _, exist := s.stateObjectsDirty[addr]; !exist {
  900. s.stateObjectsDirty[addr] = struct{}{}
  901. // At this point, also ship the address off to the precacher. The precacher
  902. // will start loading tries, and when the change is eventually committed,
  903. // the commit-phase will be a lot faster
  904. addressesToPrefetch = append(addressesToPrefetch, common.CopyBytes(addr[:])) // Copy needed for closure
  905. }
  906. }
  907. if s.prefetcher != nil && len(addressesToPrefetch) > 0 {
  908. s.prefetcher.prefetch(s.originalRoot, addressesToPrefetch, emptyAddr)
  909. }
  910. // Invalidate journal because reverting across transactions is not allowed.
  911. s.clearJournalAndRefund()
  912. }
  913. // IntermediateRoot computes the current root hash of the state trie.
  914. // It is called in between transactions to get the root hash that
  915. // goes into transaction receipts.
  916. func (s *StateDB) IntermediateRoot(deleteEmptyObjects bool) common.Hash {
  917. if s.lightProcessed {
  918. s.StopPrefetcher()
  919. return s.trie.Hash()
  920. }
  921. // Finalise all the dirty storage states and write them into the tries
  922. s.Finalise(deleteEmptyObjects)
  923. s.AccountsIntermediateRoot()
  924. return s.StateIntermediateRoot()
  925. }
  926. func (s *StateDB) AccountsIntermediateRoot() {
  927. tasks := make(chan func())
  928. finishCh := make(chan struct{})
  929. defer close(finishCh)
  930. wg := sync.WaitGroup{}
  931. for i := 0; i < runtime.NumCPU(); i++ {
  932. go func() {
  933. for {
  934. select {
  935. case task := <-tasks:
  936. task()
  937. case <-finishCh:
  938. return
  939. }
  940. }
  941. }()
  942. }
  943. // Although naively it makes sense to retrieve the account trie and then do
  944. // the contract storage and account updates sequentially, that short circuits
  945. // the account prefetcher. Instead, let's process all the storage updates
  946. // first, giving the account prefeches just a few more milliseconds of time
  947. // to pull useful data from disk.
  948. for addr := range s.stateObjectsPending {
  949. if obj := s.stateObjects[addr]; !obj.deleted {
  950. wg.Add(1)
  951. tasks <- func() {
  952. obj.updateRoot(s.db)
  953. // If state snapshotting is active, cache the data til commit. Note, this
  954. // update mechanism is not symmetric to the deletion, because whereas it is
  955. // enough to track account updates at commit time, deletions need tracking
  956. // at transaction boundary level to ensure we capture state clearing.
  957. if s.snap != nil && !obj.deleted {
  958. s.snapMux.Lock()
  959. // It is possible to add unnecessary change, but it is fine.
  960. s.snapAccounts[obj.address] = snapshot.SlimAccountRLP(obj.data.Nonce, obj.data.Balance, obj.data.Root, obj.data.CodeHash)
  961. s.snapMux.Unlock()
  962. }
  963. data, err := rlp.EncodeToBytes(obj)
  964. if err != nil {
  965. panic(fmt.Errorf("can't encode object at %x: %v", addr[:], err))
  966. }
  967. obj.encodeData = data
  968. wg.Done()
  969. }
  970. }
  971. }
  972. wg.Wait()
  973. }
  974. func (s *StateDB) StateIntermediateRoot() common.Hash {
  975. // If there was a trie prefetcher operating, it gets aborted and irrevocably
  976. // modified after we start retrieving tries. Remove it from the statedb after
  977. // this round of use.
  978. //
  979. // This is weird pre-byzantium since the first tx runs with a prefetcher and
  980. // the remainder without, but pre-byzantium even the initial prefetcher is
  981. // useless, so no sleep lost.
  982. prefetcher := s.prefetcher
  983. defer func() {
  984. s.prefetcherLock.Lock()
  985. if s.prefetcher != nil {
  986. s.prefetcher.close()
  987. s.prefetcher = nil
  988. }
  989. // try not use defer inside defer
  990. s.prefetcherLock.Unlock()
  991. }()
  992. // Now we're about to start to write changes to the trie. The trie is so far
  993. // _untouched_. We can check with the prefetcher, if it can give us a trie
  994. // which has the same root, but also has some content loaded into it.
  995. if prefetcher != nil {
  996. if trie := prefetcher.trie(s.originalRoot); trie != nil {
  997. s.trie = trie
  998. }
  999. }
  1000. if s.trie == nil {
  1001. tr, err := s.db.OpenTrie(s.originalRoot)
  1002. if err != nil {
  1003. panic(fmt.Sprintf("Failed to open trie tree %s", s.originalRoot))
  1004. }
  1005. s.trie = tr
  1006. }
  1007. usedAddrs := make([][]byte, 0, len(s.stateObjectsPending))
  1008. for addr := range s.stateObjectsPending {
  1009. if obj := s.stateObjects[addr]; obj.deleted {
  1010. s.deleteStateObject(obj)
  1011. } else {
  1012. s.updateStateObject(obj)
  1013. }
  1014. usedAddrs = append(usedAddrs, common.CopyBytes(addr[:])) // Copy needed for closure
  1015. }
  1016. if prefetcher != nil {
  1017. prefetcher.used(s.originalRoot, usedAddrs)
  1018. }
  1019. if len(s.stateObjectsPending) > 0 {
  1020. s.stateObjectsPending = make(map[common.Address]struct{})
  1021. }
  1022. // Track the amount of time wasted on hashing the account trie
  1023. if metrics.EnabledExpensive {
  1024. defer func(start time.Time) { s.AccountHashes += time.Since(start) }(time.Now())
  1025. }
  1026. root := s.trie.Hash()
  1027. return root
  1028. }
  1029. // Prepare sets the current transaction hash and index and block hash which is
  1030. // used when the EVM emits new state logs.
  1031. func (s *StateDB) Prepare(thash, bhash common.Hash, ti int) {
  1032. s.thash = thash
  1033. s.bhash = bhash
  1034. s.txIndex = ti
  1035. s.accessList = nil
  1036. }
  1037. func (s *StateDB) clearJournalAndRefund() {
  1038. if len(s.journal.entries) > 0 {
  1039. s.journal = newJournal()
  1040. s.refund = 0
  1041. }
  1042. s.validRevisions = s.validRevisions[:0] // Snapshots can be created without journal entires
  1043. }
  1044. func (s *StateDB) LightCommit() (common.Hash, *types.DiffLayer, error) {
  1045. codeWriter := s.db.TrieDB().DiskDB().NewBatch()
  1046. // light process already verified it, expectedRoot is trustworthy.
  1047. root := s.expectedRoot
  1048. commitFuncs := []func() error{
  1049. func() error {
  1050. for codeHash, code := range s.diffCode {
  1051. rawdb.WriteCode(codeWriter, codeHash, code)
  1052. if codeWriter.ValueSize() >= ethdb.IdealBatchSize {
  1053. if err := codeWriter.Write(); err != nil {
  1054. return err
  1055. }
  1056. codeWriter.Reset()
  1057. }
  1058. }
  1059. if codeWriter.ValueSize() > 0 {
  1060. if err := codeWriter.Write(); err != nil {
  1061. return err
  1062. }
  1063. }
  1064. return nil
  1065. },
  1066. func() error {
  1067. tasks := make(chan func())
  1068. taskResults := make(chan error, len(s.diffTries))
  1069. tasksNum := 0
  1070. finishCh := make(chan struct{})
  1071. defer close(finishCh)
  1072. threads := gopool.Threads(len(s.diffTries))
  1073. for i := 0; i < threads; i++ {
  1074. go func() {
  1075. for {
  1076. select {
  1077. case task := <-tasks:
  1078. task()
  1079. case <-finishCh:
  1080. return
  1081. }
  1082. }
  1083. }()
  1084. }
  1085. for account, diff := range s.diffTries {
  1086. tmpAccount := account
  1087. tmpDiff := diff
  1088. tasks <- func() {
  1089. root, err := tmpDiff.Commit(nil)
  1090. if err != nil {
  1091. taskResults <- err
  1092. return
  1093. }
  1094. s.db.CacheStorage(crypto.Keccak256Hash(tmpAccount[:]), root, tmpDiff)
  1095. taskResults <- nil
  1096. }
  1097. tasksNum++
  1098. }
  1099. for i := 0; i < tasksNum; i++ {
  1100. err := <-taskResults
  1101. if err != nil {
  1102. return err
  1103. }
  1104. }
  1105. // commit account trie
  1106. var account Account
  1107. root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error {
  1108. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  1109. return nil
  1110. }
  1111. if account.Root != emptyRoot {
  1112. s.db.TrieDB().Reference(account.Root, parent)
  1113. }
  1114. return nil
  1115. })
  1116. if err != nil {
  1117. return err
  1118. }
  1119. if root != emptyRoot {
  1120. s.db.CacheAccount(root, s.trie)
  1121. }
  1122. return nil
  1123. },
  1124. func() error {
  1125. if s.snap != nil {
  1126. if metrics.EnabledExpensive {
  1127. defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
  1128. }
  1129. // Only update if there's a state transition (skip empty Clique blocks)
  1130. if parent := s.snap.Root(); parent != root {
  1131. // for light commit, always do sync commit
  1132. if err := s.snaps.Update(root, parent, s.snapDestructs, s.snapAccounts, s.snapStorage, nil); err != nil {
  1133. log.Warn("Failed to update snapshot tree", "from", parent, "to", root, "err", err)
  1134. }
  1135. // Keep n diff layers in the memory
  1136. // - head layer is paired with HEAD state
  1137. // - head-1 layer is paired with HEAD-1 state
  1138. // - head-(n-1) layer(bottom-most diff layer) is paired with HEAD-(n-1)state
  1139. if err := s.snaps.Cap(root, s.snaps.CapLimit()); err != nil {
  1140. log.Warn("Failed to cap snapshot tree", "root", root, "layers", s.snaps.CapLimit(), "err", err)
  1141. }
  1142. }
  1143. }
  1144. return nil
  1145. },
  1146. }
  1147. commitRes := make(chan error, len(commitFuncs))
  1148. for _, f := range commitFuncs {
  1149. tmpFunc := f
  1150. go func() {
  1151. commitRes <- tmpFunc()
  1152. }()
  1153. }
  1154. for i := 0; i < len(commitFuncs); i++ {
  1155. r := <-commitRes
  1156. if r != nil {
  1157. return common.Hash{}, nil, r
  1158. }
  1159. }
  1160. s.snap, s.snapDestructs, s.snapAccounts, s.snapStorage = nil, nil, nil, nil
  1161. s.diffTries, s.diffCode = nil, nil
  1162. return root, s.diffLayer, nil
  1163. }
  1164. // Commit writes the state to the underlying in-memory trie database.
  1165. func (s *StateDB) Commit(failPostCommitFunc func(), postCommitFuncs ...func() error) (common.Hash, *types.DiffLayer, error) {
  1166. if s.dbErr != nil {
  1167. return common.Hash{}, nil, fmt.Errorf("commit aborted due to earlier error: %v", s.dbErr)
  1168. }
  1169. // Finalize any pending changes and merge everything into the tries
  1170. if s.lightProcessed {
  1171. root, diff, err := s.LightCommit()
  1172. if err != nil {
  1173. return root, diff, err
  1174. }
  1175. for _, postFunc := range postCommitFuncs {
  1176. err = postFunc()
  1177. if err != nil {
  1178. return root, diff, err
  1179. }
  1180. }
  1181. return root, diff, nil
  1182. }
  1183. var diffLayer *types.DiffLayer
  1184. var verified chan struct{}
  1185. var snapUpdated chan struct{}
  1186. if s.snap != nil {
  1187. diffLayer = &types.DiffLayer{}
  1188. }
  1189. if s.pipeCommit {
  1190. // async commit the MPT
  1191. verified = make(chan struct{})
  1192. snapUpdated = make(chan struct{})
  1193. }
  1194. commmitTrie := func() error {
  1195. commitErr := func() error {
  1196. if s.stateRoot = s.StateIntermediateRoot(); s.fullProcessed && s.expectedRoot != s.stateRoot {
  1197. return fmt.Errorf("invalid merkle root (remote: %x local: %x)", s.expectedRoot, s.stateRoot)
  1198. }
  1199. tasks := make(chan func())
  1200. taskResults := make(chan error, len(s.stateObjectsDirty))
  1201. tasksNum := 0
  1202. finishCh := make(chan struct{})
  1203. threads := gopool.Threads(len(s.stateObjectsDirty))
  1204. wg := sync.WaitGroup{}
  1205. for i := 0; i < threads; i++ {
  1206. wg.Add(1)
  1207. go func() {
  1208. defer wg.Done()
  1209. for {
  1210. select {
  1211. case task := <-tasks:
  1212. task()
  1213. case <-finishCh:
  1214. return
  1215. }
  1216. }
  1217. }()
  1218. }
  1219. if s.snap != nil {
  1220. for addr := range s.stateObjectsDirty {
  1221. if obj := s.stateObjects[addr]; !obj.deleted {
  1222. if obj.code != nil && obj.dirtyCode {
  1223. diffLayer.Codes = append(diffLayer.Codes, types.DiffCode{
  1224. Hash: common.BytesToHash(obj.CodeHash()),
  1225. Code: obj.code,
  1226. })
  1227. }
  1228. }
  1229. }
  1230. }
  1231. for addr := range s.stateObjectsDirty {
  1232. if obj := s.stateObjects[addr]; !obj.deleted {
  1233. // Write any contract code associated with the state object
  1234. tasks <- func() {
  1235. // Write any storage changes in the state object to its storage trie
  1236. if err := obj.CommitTrie(s.db); err != nil {
  1237. taskResults <- err
  1238. }
  1239. taskResults <- nil
  1240. }
  1241. tasksNum++
  1242. }
  1243. }
  1244. for i := 0; i < tasksNum; i++ {
  1245. err := <-taskResults
  1246. if err != nil {
  1247. close(finishCh)
  1248. return err
  1249. }
  1250. }
  1251. close(finishCh)
  1252. // The onleaf func is called _serially_, so we can reuse the same account
  1253. // for unmarshalling every time.
  1254. var account Account
  1255. root, err := s.trie.Commit(func(_ [][]byte, _ []byte, leaf []byte, parent common.Hash) error {
  1256. if err := rlp.DecodeBytes(leaf, &account); err != nil {
  1257. return nil
  1258. }
  1259. if account.Root != emptyRoot {
  1260. s.db.TrieDB().Reference(account.Root, parent)
  1261. }
  1262. return nil
  1263. })
  1264. if err != nil {
  1265. return err
  1266. }
  1267. if root != emptyRoot {
  1268. s.db.CacheAccount(root, s.trie)
  1269. }
  1270. for _, postFunc := range postCommitFuncs {
  1271. err = postFunc()
  1272. if err != nil {
  1273. return err
  1274. }
  1275. }
  1276. wg.Wait()
  1277. return nil
  1278. }()
  1279. if s.pipeCommit {
  1280. if commitErr == nil {
  1281. <-snapUpdated
  1282. s.snaps.Snapshot(s.stateRoot).MarkValid()
  1283. } else {
  1284. // The blockchain will do the further rewind if write block not finish yet
  1285. if failPostCommitFunc != nil {
  1286. <-snapUpdated
  1287. failPostCommitFunc()
  1288. }
  1289. log.Error("state verification failed", "err", commitErr)
  1290. }
  1291. close(verified)
  1292. }
  1293. return commitErr
  1294. }
  1295. commitFuncs := []func() error{
  1296. func() error {
  1297. codeWriter := s.db.TrieDB().DiskDB().NewBatch()
  1298. for addr := range s.stateObjectsDirty {
  1299. if obj := s.stateObjects[addr]; !obj.deleted {
  1300. if obj.code != nil && obj.dirtyCode {
  1301. rawdb.WriteCode(codeWriter, common.BytesToHash(obj.CodeHash()), obj.code)
  1302. obj.dirtyCode = false
  1303. if codeWriter.ValueSize() > ethdb.IdealBatchSize {
  1304. if err := codeWriter.Write(); err != nil {
  1305. return err
  1306. }
  1307. codeWriter.Reset()
  1308. }
  1309. }
  1310. }
  1311. }
  1312. if codeWriter.ValueSize() > 0 {
  1313. if err := codeWriter.Write(); err != nil {
  1314. log.Crit("Failed to commit dirty codes", "error", err)
  1315. return err
  1316. }
  1317. }
  1318. return nil
  1319. },
  1320. func() error {
  1321. // If snapshotting is enabled, update the snapshot tree with this new version
  1322. if s.snap != nil {
  1323. if metrics.EnabledExpensive {
  1324. defer func(start time.Time) { s.SnapshotCommits += time.Since(start) }(time.Now())
  1325. }
  1326. if s.pipeCommit {
  1327. defer close(snapUpdated)
  1328. }
  1329. // Only update if there's a state transition (skip empty Clique blocks)
  1330. if parent := s.snap.Root(); parent != s.expectedRoot {
  1331. if err := s.snaps.Update(s.expectedRoot, parent, s.snapDestructs, s.snapAccounts, s.snapStorage, verified); err != nil {
  1332. log.Warn("Failed to update snapshot tree", "from", parent, "to", s.expectedRoot, "err", err)
  1333. }
  1334. // Keep n diff layers in the memory
  1335. // - head layer is paired with HEAD state
  1336. // - head-1 layer is paired with HEAD-1 state
  1337. // - head-(n-1) layer(bottom-most diff layer) is paired with HEAD-(n-1)state
  1338. go func() {
  1339. if err := s.snaps.Cap(s.expectedRoot, s.snaps.CapLimit()); err != nil {
  1340. log.Warn("Failed to cap snapshot tree", "root", s.expectedRoot, "layers", s.snaps.CapLimit(), "err", err)
  1341. }
  1342. }()
  1343. }
  1344. }
  1345. return nil
  1346. },
  1347. func() error {
  1348. if s.snap != nil {
  1349. diffLayer.Destructs, diffLayer.Accounts, diffLayer.Storages = s.SnapToDiffLayer()
  1350. }
  1351. return nil
  1352. },
  1353. }
  1354. if s.pipeCommit {
  1355. go commmitTrie()
  1356. } else {
  1357. commitFuncs = append(commitFuncs, commmitTrie)
  1358. }
  1359. commitRes := make(chan error, len(commitFuncs))
  1360. for _, f := range commitFuncs {
  1361. tmpFunc := f
  1362. go func() {
  1363. commitRes <- tmpFunc()
  1364. }()
  1365. }
  1366. for i := 0; i < len(commitFuncs); i++ {
  1367. r := <-commitRes
  1368. if r != nil {
  1369. return common.Hash{}, nil, r
  1370. }
  1371. }
  1372. root := s.stateRoot
  1373. if s.pipeCommit {
  1374. root = s.expectedRoot
  1375. }
  1376. return root, diffLayer, nil
  1377. }
  1378. func (s *StateDB) DiffLayerToSnap(diffLayer *types.DiffLayer) (map[common.Address]struct{}, map[common.Address][]byte, map[common.Address]map[string][]byte, error) {
  1379. snapDestructs := make(map[common.Address]struct{})
  1380. snapAccounts := make(map[common.Address][]byte)
  1381. snapStorage := make(map[common.Address]map[string][]byte)
  1382. for _, des := range diffLayer.Destructs {
  1383. snapDestructs[des] = struct{}{}
  1384. }
  1385. for _, account := range diffLayer.Accounts {
  1386. snapAccounts[account.Account] = account.Blob
  1387. }
  1388. for _, storage := range diffLayer.Storages {
  1389. // should never happen
  1390. if len(storage.Keys) != len(storage.Vals) {
  1391. return nil, nil, nil, errors.New("invalid diffLayer: length of keys and values mismatch")
  1392. }
  1393. snapStorage[storage.Account] = make(map[string][]byte, len(storage.Keys))
  1394. n := len(storage.Keys)
  1395. for i := 0; i < n; i++ {
  1396. snapStorage[storage.Account][storage.Keys[i]] = storage.Vals[i]
  1397. }
  1398. }
  1399. return snapDestructs, snapAccounts, snapStorage, nil
  1400. }
  1401. func (s *StateDB) SnapToDiffLayer() ([]common.Address, []types.DiffAccount, []types.DiffStorage) {
  1402. destructs := make([]common.Address, 0, len(s.snapDestructs))
  1403. for account := range s.snapDestructs {
  1404. destructs = append(destructs, account)
  1405. }
  1406. accounts := make([]types.DiffAccount, 0, len(s.snapAccounts))
  1407. for accountHash, account := range s.snapAccounts {
  1408. accounts = append(accounts, types.DiffAccount{
  1409. Account: accountHash,
  1410. Blob: account,
  1411. })
  1412. }
  1413. storages := make([]types.DiffStorage, 0, len(s.snapStorage))
  1414. for accountHash, storage := range s.snapStorage {
  1415. keys := make([]string, 0, len(storage))
  1416. values := make([][]byte, 0, len(storage))
  1417. for k, v := range storage {
  1418. keys = append(keys, k)
  1419. values = append(values, v)
  1420. }
  1421. storages = append(storages, types.DiffStorage{
  1422. Account: accountHash,
  1423. Keys: keys,
  1424. Vals: values,
  1425. })
  1426. }
  1427. return destructs, accounts, storages
  1428. }
  1429. // PrepareAccessList handles the preparatory steps for executing a state transition with
  1430. // regards to both EIP-2929 and EIP-2930:
  1431. //
  1432. // - Add sender to access list (2929)
  1433. // - Add destination to access list (2929)
  1434. // - Add precompiles to access list (2929)
  1435. // - Add the contents of the optional tx access list (2930)
  1436. //
  1437. // This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.
  1438. func (s *StateDB) PrepareAccessList(sender common.Address, dst *common.Address, precompiles []common.Address, list types.AccessList) {
  1439. s.AddAddressToAccessList(sender)
  1440. if dst != nil {
  1441. s.AddAddressToAccessList(*dst)
  1442. // If it's a create-tx, the destination will be added inside evm.create
  1443. }
  1444. for _, addr := range precompiles {
  1445. s.AddAddressToAccessList(addr)
  1446. }
  1447. for _, el := range list {
  1448. s.AddAddressToAccessList(el.Address)
  1449. for _, key := range el.StorageKeys {
  1450. s.AddSlotToAccessList(el.Address, key)
  1451. }
  1452. }
  1453. }
  1454. // AddAddressToAccessList adds the given address to the access list
  1455. func (s *StateDB) AddAddressToAccessList(addr common.Address) {
  1456. if s.accessList == nil {
  1457. s.accessList = newAccessList()
  1458. }
  1459. if s.accessList.AddAddress(addr) {
  1460. s.journal.append(accessListAddAccountChange{&addr})
  1461. }
  1462. }
  1463. // AddSlotToAccessList adds the given (address, slot)-tuple to the access list
  1464. func (s *StateDB) AddSlotToAccessList(addr common.Address, slot common.Hash) {
  1465. if s.accessList == nil {
  1466. s.accessList = newAccessList()
  1467. }
  1468. addrMod, slotMod := s.accessList.AddSlot(addr, slot)
  1469. if addrMod {
  1470. // In practice, this should not happen, since there is no way to enter the
  1471. // scope of 'address' without having the 'address' become already added
  1472. // to the access list (via call-variant, create, etc).
  1473. // Better safe than sorry, though
  1474. s.journal.append(accessListAddAccountChange{&addr})
  1475. }
  1476. if slotMod {
  1477. s.journal.append(accessListAddSlotChange{
  1478. address: &addr,
  1479. slot: &slot,
  1480. })
  1481. }
  1482. }
  1483. // AddressInAccessList returns true if the given address is in the access list.
  1484. func (s *StateDB) AddressInAccessList(addr common.Address) bool {
  1485. if s.accessList == nil {
  1486. return false
  1487. }
  1488. return s.accessList.ContainsAddress(addr)
  1489. }
  1490. // SlotInAccessList returns true if the given (address, slot)-tuple is in the access list.
  1491. func (s *StateDB) SlotInAccessList(addr common.Address, slot common.Hash) (addressPresent bool, slotPresent bool) {
  1492. if s.accessList == nil {
  1493. return false, false
  1494. }
  1495. return s.accessList.Contains(addr, slot)
  1496. }
  1497. func (s *StateDB) GetDirtyAccounts() []common.Address {
  1498. accounts := make([]common.Address, 0, len(s.stateObjectsDirty))
  1499. for account := range s.stateObjectsDirty {
  1500. accounts = append(accounts, account)
  1501. }
  1502. return accounts
  1503. }