statedb_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. // Copyright 2016 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
  17. import (
  18. "bytes"
  19. "encoding/binary"
  20. "fmt"
  21. "math"
  22. "math/big"
  23. "math/rand"
  24. "reflect"
  25. "strings"
  26. "sync"
  27. "testing"
  28. "testing/quick"
  29. "github.com/ethereum/go-ethereum/common"
  30. "github.com/ethereum/go-ethereum/core/rawdb"
  31. "github.com/ethereum/go-ethereum/core/types"
  32. )
  33. // Tests that updating a state trie does not leak any database writes prior to
  34. // actually committing the state.
  35. func TestUpdateLeaks(t *testing.T) {
  36. // Create an empty state database
  37. db := rawdb.NewMemoryDatabase()
  38. state, _ := New(common.Hash{}, NewDatabase(db), nil)
  39. // Update it with some accounts
  40. for i := byte(0); i < 255; i++ {
  41. addr := common.BytesToAddress([]byte{i})
  42. state.AddBalance(addr, big.NewInt(int64(11*i)))
  43. state.SetNonce(addr, uint64(42*i))
  44. if i%2 == 0 {
  45. state.SetState(addr, common.BytesToHash([]byte{i, i, i}), common.BytesToHash([]byte{i, i, i, i}))
  46. }
  47. if i%3 == 0 {
  48. state.SetCode(addr, []byte{i, i, i, i, i})
  49. }
  50. }
  51. root := state.IntermediateRoot(false)
  52. if err := state.Database().TrieDB().Commit(root, false, nil); err != nil {
  53. t.Errorf("can not commit trie %v to persistent database", root.Hex())
  54. }
  55. // Ensure that no data was leaked into the database
  56. it := db.NewIterator(nil, nil)
  57. for it.Next() {
  58. t.Errorf("State leaked into database: %x -> %x", it.Key(), it.Value())
  59. }
  60. it.Release()
  61. }
  62. // Tests that no intermediate state of an object is stored into the database,
  63. // only the one right before the commit.
  64. func TestIntermediateLeaks(t *testing.T) {
  65. // Create two state databases, one transitioning to the final state, the other final from the beginning
  66. transDb := rawdb.NewMemoryDatabase()
  67. finalDb := rawdb.NewMemoryDatabase()
  68. transState, _ := New(common.Hash{}, NewDatabase(transDb), nil)
  69. finalState, _ := New(common.Hash{}, NewDatabase(finalDb), nil)
  70. modify := func(state *StateDB, addr common.Address, i, tweak byte) {
  71. state.SetBalance(addr, big.NewInt(int64(11*i)+int64(tweak)))
  72. state.SetNonce(addr, uint64(42*i+tweak))
  73. if i%2 == 0 {
  74. state.SetState(addr, common.Hash{i, i, i, 0}, common.Hash{})
  75. state.SetState(addr, common.Hash{i, i, i, tweak}, common.Hash{i, i, i, i, tweak})
  76. }
  77. if i%3 == 0 {
  78. state.SetCode(addr, []byte{i, i, i, i, i, tweak})
  79. }
  80. }
  81. // Modify the transient state.
  82. for i := byte(0); i < 255; i++ {
  83. modify(transState, common.Address{i}, i, 0)
  84. }
  85. // Write modifications to trie.
  86. transState.IntermediateRoot(false)
  87. // Overwrite all the data with new values in the transient database.
  88. for i := byte(0); i < 255; i++ {
  89. modify(transState, common.Address{i}, i, 99)
  90. modify(finalState, common.Address{i}, i, 99)
  91. }
  92. // Commit and cross check the databases.
  93. transState.Finalise(false)
  94. transState.AccountsIntermediateRoot()
  95. transRoot, _, err := transState.Commit(nil)
  96. if err != nil {
  97. t.Fatalf("failed to commit transition state: %v", err)
  98. }
  99. if err = transState.Database().TrieDB().Commit(transRoot, false, nil); err != nil {
  100. t.Errorf("can not commit trie %v to persistent database", transRoot.Hex())
  101. }
  102. finalState.Finalise(false)
  103. finalState.AccountsIntermediateRoot()
  104. finalRoot, _, err := finalState.Commit(nil)
  105. if err != nil {
  106. t.Fatalf("failed to commit final state: %v", err)
  107. }
  108. if err = finalState.Database().TrieDB().Commit(finalRoot, false, nil); err != nil {
  109. t.Errorf("can not commit trie %v to persistent database", finalRoot.Hex())
  110. }
  111. it := finalDb.NewIterator(nil, nil)
  112. for it.Next() {
  113. key, fvalue := it.Key(), it.Value()
  114. tvalue, err := transDb.Get(key)
  115. if err != nil {
  116. t.Errorf("entry missing from the transition database: %x -> %x", key, fvalue)
  117. }
  118. if !bytes.Equal(fvalue, tvalue) {
  119. t.Errorf("the value associate key %x is mismatch,: %x in transition database ,%x in final database", key, tvalue, fvalue)
  120. }
  121. }
  122. it.Release()
  123. it = transDb.NewIterator(nil, nil)
  124. for it.Next() {
  125. key, tvalue := it.Key(), it.Value()
  126. fvalue, err := finalDb.Get(key)
  127. if err != nil {
  128. t.Errorf("extra entry in the transition database: %x -> %x", key, it.Value())
  129. }
  130. if !bytes.Equal(fvalue, tvalue) {
  131. t.Errorf("the value associate key %x is mismatch,: %x in transition database ,%x in final database", key, tvalue, fvalue)
  132. }
  133. }
  134. }
  135. // TestCopy tests that copying a StateDB object indeed makes the original and
  136. // the copy independent of each other. This test is a regression test against
  137. // https://github.com/ethereum/go-ethereum/pull/15549.
  138. func TestCopy(t *testing.T) {
  139. // Create a random state test to copy and modify "independently"
  140. orig, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  141. for i := byte(0); i < 255; i++ {
  142. obj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  143. obj.AddBalance(big.NewInt(int64(i)))
  144. orig.updateStateObject(obj)
  145. }
  146. orig.Finalise(false)
  147. // Copy the state
  148. copy := orig.Copy()
  149. // Copy the copy state
  150. ccopy := copy.Copy()
  151. // modify all in memory
  152. for i := byte(0); i < 255; i++ {
  153. origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  154. copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  155. ccopyObj := ccopy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  156. origObj.AddBalance(big.NewInt(2 * int64(i)))
  157. copyObj.AddBalance(big.NewInt(3 * int64(i)))
  158. ccopyObj.AddBalance(big.NewInt(4 * int64(i)))
  159. orig.updateStateObject(origObj)
  160. copy.updateStateObject(copyObj)
  161. ccopy.updateStateObject(copyObj)
  162. }
  163. // Finalise the changes on all concurrently
  164. finalise := func(wg *sync.WaitGroup, db *StateDB) {
  165. defer wg.Done()
  166. db.Finalise(true)
  167. }
  168. var wg sync.WaitGroup
  169. wg.Add(3)
  170. go finalise(&wg, orig)
  171. go finalise(&wg, copy)
  172. go finalise(&wg, ccopy)
  173. wg.Wait()
  174. // Verify that the three states have been updated independently
  175. for i := byte(0); i < 255; i++ {
  176. origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  177. copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  178. ccopyObj := ccopy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  179. if want := big.NewInt(3 * int64(i)); origObj.Balance().Cmp(want) != 0 {
  180. t.Errorf("orig obj %d: balance mismatch: have %v, want %v", i, origObj.Balance(), want)
  181. }
  182. if want := big.NewInt(4 * int64(i)); copyObj.Balance().Cmp(want) != 0 {
  183. t.Errorf("copy obj %d: balance mismatch: have %v, want %v", i, copyObj.Balance(), want)
  184. }
  185. if want := big.NewInt(5 * int64(i)); ccopyObj.Balance().Cmp(want) != 0 {
  186. t.Errorf("copy obj %d: balance mismatch: have %v, want %v", i, ccopyObj.Balance(), want)
  187. }
  188. }
  189. }
  190. func TestSnapshotRandom(t *testing.T) {
  191. config := &quick.Config{MaxCount: 1000}
  192. err := quick.Check((*snapshotTest).run, config)
  193. if cerr, ok := err.(*quick.CheckError); ok {
  194. test := cerr.In[0].(*snapshotTest)
  195. t.Errorf("%v:\n%s", test.err, test)
  196. } else if err != nil {
  197. t.Error(err)
  198. }
  199. }
  200. // A snapshotTest checks that reverting StateDB snapshots properly undoes all changes
  201. // captured by the snapshot. Instances of this test with pseudorandom content are created
  202. // by Generate.
  203. //
  204. // The test works as follows:
  205. //
  206. // A new state is created and all actions are applied to it. Several snapshots are taken
  207. // in between actions. The test then reverts each snapshot. For each snapshot the actions
  208. // leading up to it are replayed on a fresh, empty state. The behaviour of all public
  209. // accessor methods on the reverted state must match the return value of the equivalent
  210. // methods on the replayed state.
  211. type snapshotTest struct {
  212. addrs []common.Address // all account addresses
  213. actions []testAction // modifications to the state
  214. snapshots []int // actions indexes at which snapshot is taken
  215. err error // failure details are reported through this field
  216. }
  217. type testAction struct {
  218. name string
  219. fn func(testAction, *StateDB)
  220. args []int64
  221. noAddr bool
  222. }
  223. // newTestAction creates a random action that changes state.
  224. func newTestAction(addr common.Address, r *rand.Rand) testAction {
  225. actions := []testAction{
  226. {
  227. name: "SetBalance",
  228. fn: func(a testAction, s *StateDB) {
  229. s.SetBalance(addr, big.NewInt(a.args[0]))
  230. },
  231. args: make([]int64, 1),
  232. },
  233. {
  234. name: "AddBalance",
  235. fn: func(a testAction, s *StateDB) {
  236. s.AddBalance(addr, big.NewInt(a.args[0]))
  237. },
  238. args: make([]int64, 1),
  239. },
  240. {
  241. name: "SetNonce",
  242. fn: func(a testAction, s *StateDB) {
  243. s.SetNonce(addr, uint64(a.args[0]))
  244. },
  245. args: make([]int64, 1),
  246. },
  247. {
  248. name: "SetState",
  249. fn: func(a testAction, s *StateDB) {
  250. var key, val common.Hash
  251. binary.BigEndian.PutUint16(key[:], uint16(a.args[0]))
  252. binary.BigEndian.PutUint16(val[:], uint16(a.args[1]))
  253. s.SetState(addr, key, val)
  254. },
  255. args: make([]int64, 2),
  256. },
  257. {
  258. name: "SetCode",
  259. fn: func(a testAction, s *StateDB) {
  260. code := make([]byte, 16)
  261. binary.BigEndian.PutUint64(code, uint64(a.args[0]))
  262. binary.BigEndian.PutUint64(code[8:], uint64(a.args[1]))
  263. s.SetCode(addr, code)
  264. },
  265. args: make([]int64, 2),
  266. },
  267. {
  268. name: "CreateAccount",
  269. fn: func(a testAction, s *StateDB) {
  270. s.CreateAccount(addr)
  271. },
  272. },
  273. {
  274. name: "Suicide",
  275. fn: func(a testAction, s *StateDB) {
  276. s.Suicide(addr)
  277. },
  278. },
  279. {
  280. name: "AddRefund",
  281. fn: func(a testAction, s *StateDB) {
  282. s.AddRefund(uint64(a.args[0]))
  283. },
  284. args: make([]int64, 1),
  285. noAddr: true,
  286. },
  287. {
  288. name: "AddLog",
  289. fn: func(a testAction, s *StateDB) {
  290. data := make([]byte, 2)
  291. binary.BigEndian.PutUint16(data, uint16(a.args[0]))
  292. s.AddLog(&types.Log{Address: addr, Data: data})
  293. },
  294. args: make([]int64, 1),
  295. },
  296. {
  297. name: "AddPreimage",
  298. fn: func(a testAction, s *StateDB) {
  299. preimage := []byte{1}
  300. hash := common.BytesToHash(preimage)
  301. s.AddPreimage(hash, preimage)
  302. },
  303. args: make([]int64, 1),
  304. },
  305. {
  306. name: "AddAddressToAccessList",
  307. fn: func(a testAction, s *StateDB) {
  308. s.AddAddressToAccessList(addr)
  309. },
  310. },
  311. {
  312. name: "AddSlotToAccessList",
  313. fn: func(a testAction, s *StateDB) {
  314. s.AddSlotToAccessList(addr,
  315. common.Hash{byte(a.args[0])})
  316. },
  317. args: make([]int64, 1),
  318. },
  319. }
  320. action := actions[r.Intn(len(actions))]
  321. var nameargs []string
  322. if !action.noAddr {
  323. nameargs = append(nameargs, addr.Hex())
  324. }
  325. for i := range action.args {
  326. action.args[i] = rand.Int63n(100)
  327. nameargs = append(nameargs, fmt.Sprint(action.args[i]))
  328. }
  329. action.name += strings.Join(nameargs, ", ")
  330. return action
  331. }
  332. // Generate returns a new snapshot test of the given size. All randomness is
  333. // derived from r.
  334. func (*snapshotTest) Generate(r *rand.Rand, size int) reflect.Value {
  335. // Generate random actions.
  336. addrs := make([]common.Address, 50)
  337. for i := range addrs {
  338. addrs[i][0] = byte(i)
  339. }
  340. actions := make([]testAction, size)
  341. for i := range actions {
  342. addr := addrs[r.Intn(len(addrs))]
  343. actions[i] = newTestAction(addr, r)
  344. }
  345. // Generate snapshot indexes.
  346. nsnapshots := int(math.Sqrt(float64(size)))
  347. if size > 0 && nsnapshots == 0 {
  348. nsnapshots = 1
  349. }
  350. snapshots := make([]int, nsnapshots)
  351. snaplen := len(actions) / nsnapshots
  352. for i := range snapshots {
  353. // Try to place the snapshots some number of actions apart from each other.
  354. snapshots[i] = (i * snaplen) + r.Intn(snaplen)
  355. }
  356. return reflect.ValueOf(&snapshotTest{addrs, actions, snapshots, nil})
  357. }
  358. func (test *snapshotTest) String() string {
  359. out := new(bytes.Buffer)
  360. sindex := 0
  361. for i, action := range test.actions {
  362. if len(test.snapshots) > sindex && i == test.snapshots[sindex] {
  363. fmt.Fprintf(out, "---- snapshot %d ----\n", sindex)
  364. sindex++
  365. }
  366. fmt.Fprintf(out, "%4d: %s\n", i, action.name)
  367. }
  368. return out.String()
  369. }
  370. func (test *snapshotTest) run() bool {
  371. // Run all actions and create snapshots.
  372. var (
  373. state, _ = New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  374. snapshotRevs = make([]int, len(test.snapshots))
  375. sindex = 0
  376. )
  377. for i, action := range test.actions {
  378. if len(test.snapshots) > sindex && i == test.snapshots[sindex] {
  379. snapshotRevs[sindex] = state.Snapshot()
  380. sindex++
  381. }
  382. action.fn(action, state)
  383. }
  384. // Revert all snapshots in reverse order. Each revert must yield a state
  385. // that is equivalent to fresh state with all actions up the snapshot applied.
  386. for sindex--; sindex >= 0; sindex-- {
  387. checkstate, _ := New(common.Hash{}, state.Database(), nil)
  388. for _, action := range test.actions[:test.snapshots[sindex]] {
  389. action.fn(action, checkstate)
  390. }
  391. state.RevertToSnapshot(snapshotRevs[sindex])
  392. if err := test.checkEqual(state, checkstate); err != nil {
  393. test.err = fmt.Errorf("state mismatch after revert to snapshot %d\n%v", sindex, err)
  394. return false
  395. }
  396. }
  397. return true
  398. }
  399. // checkEqual checks that methods of state and checkstate return the same values.
  400. func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error {
  401. for _, addr := range test.addrs {
  402. var err error
  403. checkeq := func(op string, a, b interface{}) bool {
  404. if err == nil && !reflect.DeepEqual(a, b) {
  405. err = fmt.Errorf("got %s(%s) == %v, want %v", op, addr.Hex(), a, b)
  406. return false
  407. }
  408. return true
  409. }
  410. // Check basic accessor methods.
  411. checkeq("Exist", state.Exist(addr), checkstate.Exist(addr))
  412. checkeq("HasSuicided", state.HasSuicided(addr), checkstate.HasSuicided(addr))
  413. checkeq("GetBalance", state.GetBalance(addr), checkstate.GetBalance(addr))
  414. checkeq("GetNonce", state.GetNonce(addr), checkstate.GetNonce(addr))
  415. checkeq("GetCode", state.GetCode(addr), checkstate.GetCode(addr))
  416. checkeq("GetCodeHash", state.GetCodeHash(addr), checkstate.GetCodeHash(addr))
  417. checkeq("GetCodeSize", state.GetCodeSize(addr), checkstate.GetCodeSize(addr))
  418. // Check storage.
  419. if obj := state.getStateObject(addr); obj != nil {
  420. state.ForEachStorage(addr, func(key, value common.Hash) bool {
  421. return checkeq("GetState("+key.Hex()+")", checkstate.GetState(addr, key), value)
  422. })
  423. checkstate.ForEachStorage(addr, func(key, value common.Hash) bool {
  424. return checkeq("GetState("+key.Hex()+")", checkstate.GetState(addr, key), value)
  425. })
  426. }
  427. if err != nil {
  428. return err
  429. }
  430. }
  431. if state.GetRefund() != checkstate.GetRefund() {
  432. return fmt.Errorf("got GetRefund() == %d, want GetRefund() == %d",
  433. state.GetRefund(), checkstate.GetRefund())
  434. }
  435. if !reflect.DeepEqual(state.GetLogs(common.Hash{}), checkstate.GetLogs(common.Hash{})) {
  436. return fmt.Errorf("got GetLogs(common.Hash{}) == %v, want GetLogs(common.Hash{}) == %v",
  437. state.GetLogs(common.Hash{}), checkstate.GetLogs(common.Hash{}))
  438. }
  439. return nil
  440. }
  441. func TestTouchDelete(t *testing.T) {
  442. s := newStateTest()
  443. s.state.GetOrNewStateObject(common.Address{})
  444. root, _, _ := s.state.Commit(nil)
  445. s.state, _ = New(root, s.state.db, s.state.snaps)
  446. snapshot := s.state.Snapshot()
  447. s.state.AddBalance(common.Address{}, new(big.Int))
  448. if len(s.state.journal.dirties) != 1 {
  449. t.Fatal("expected one dirty state object")
  450. }
  451. s.state.RevertToSnapshot(snapshot)
  452. if len(s.state.journal.dirties) != 0 {
  453. t.Fatal("expected no dirty state object")
  454. }
  455. }
  456. // TestCopyOfCopy tests that modified objects are carried over to the copy, and the copy of the copy.
  457. // See https://github.com/ethereum/go-ethereum/pull/15225#issuecomment-380191512
  458. func TestCopyOfCopy(t *testing.T) {
  459. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  460. addr := common.HexToAddress("aaaa")
  461. state.SetBalance(addr, big.NewInt(42))
  462. if got := state.Copy().GetBalance(addr).Uint64(); got != 42 {
  463. t.Fatalf("1st copy fail, expected 42, got %v", got)
  464. }
  465. if got := state.Copy().Copy().GetBalance(addr).Uint64(); got != 42 {
  466. t.Fatalf("2nd copy fail, expected 42, got %v", got)
  467. }
  468. }
  469. // Tests a regression where committing a copy lost some internal meta information,
  470. // leading to corrupted subsequent copies.
  471. //
  472. // See https://github.com/ethereum/go-ethereum/issues/20106.
  473. func TestCopyCommitCopy(t *testing.T) {
  474. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  475. // Create an account and check if the retrieved balance is correct
  476. addr := common.HexToAddress("0xaffeaffeaffeaffeaffeaffeaffeaffeaffeaffe")
  477. skey := common.HexToHash("aaa")
  478. sval := common.HexToHash("bbb")
  479. state.SetBalance(addr, big.NewInt(42)) // Change the account trie
  480. state.SetCode(addr, []byte("hello")) // Change an external metadata
  481. state.SetState(addr, skey, sval) // Change the storage trie
  482. if balance := state.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  483. t.Fatalf("initial balance mismatch: have %v, want %v", balance, 42)
  484. }
  485. if code := state.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  486. t.Fatalf("initial code mismatch: have %x, want %x", code, []byte("hello"))
  487. }
  488. if val := state.GetState(addr, skey); val != sval {
  489. t.Fatalf("initial non-committed storage slot mismatch: have %x, want %x", val, sval)
  490. }
  491. if val := state.GetCommittedState(addr, skey); val != (common.Hash{}) {
  492. t.Fatalf("initial committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  493. }
  494. // Copy the non-committed state database and check pre/post commit balance
  495. copyOne := state.Copy()
  496. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  497. t.Fatalf("first copy pre-commit balance mismatch: have %v, want %v", balance, 42)
  498. }
  499. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  500. t.Fatalf("first copy pre-commit code mismatch: have %x, want %x", code, []byte("hello"))
  501. }
  502. if val := copyOne.GetState(addr, skey); val != sval {
  503. t.Fatalf("first copy pre-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  504. }
  505. if val := copyOne.GetCommittedState(addr, skey); val != (common.Hash{}) {
  506. t.Fatalf("first copy pre-commit committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  507. }
  508. copyOne.Finalise(false)
  509. copyOne.AccountsIntermediateRoot()
  510. copyOne.Commit(nil)
  511. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  512. t.Fatalf("first copy post-commit balance mismatch: have %v, want %v", balance, 42)
  513. }
  514. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  515. t.Fatalf("first copy post-commit code mismatch: have %x, want %x", code, []byte("hello"))
  516. }
  517. if val := copyOne.GetState(addr, skey); val != sval {
  518. t.Fatalf("first copy post-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  519. }
  520. if val := copyOne.GetCommittedState(addr, skey); val != sval {
  521. t.Fatalf("first copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  522. }
  523. // Copy the copy and check the balance once more
  524. copyTwo := copyOne.Copy()
  525. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  526. t.Fatalf("second copy balance mismatch: have %v, want %v", balance, 42)
  527. }
  528. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  529. t.Fatalf("second copy code mismatch: have %x, want %x", code, []byte("hello"))
  530. }
  531. if val := copyTwo.GetState(addr, skey); val != sval {
  532. t.Fatalf("second copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  533. }
  534. if val := copyTwo.GetCommittedState(addr, skey); val != sval {
  535. t.Fatalf("second copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  536. }
  537. }
  538. // Tests a regression where committing a copy lost some internal meta information,
  539. // leading to corrupted subsequent copies.
  540. //
  541. // See https://github.com/ethereum/go-ethereum/issues/20106.
  542. func TestCopyCopyCommitCopy(t *testing.T) {
  543. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  544. // Create an account and check if the retrieved balance is correct
  545. addr := common.HexToAddress("0xaffeaffeaffeaffeaffeaffeaffeaffeaffeaffe")
  546. skey := common.HexToHash("aaa")
  547. sval := common.HexToHash("bbb")
  548. state.SetBalance(addr, big.NewInt(42)) // Change the account trie
  549. state.SetCode(addr, []byte("hello")) // Change an external metadata
  550. state.SetState(addr, skey, sval) // Change the storage trie
  551. if balance := state.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  552. t.Fatalf("initial balance mismatch: have %v, want %v", balance, 42)
  553. }
  554. if code := state.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  555. t.Fatalf("initial code mismatch: have %x, want %x", code, []byte("hello"))
  556. }
  557. if val := state.GetState(addr, skey); val != sval {
  558. t.Fatalf("initial non-committed storage slot mismatch: have %x, want %x", val, sval)
  559. }
  560. if val := state.GetCommittedState(addr, skey); val != (common.Hash{}) {
  561. t.Fatalf("initial committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  562. }
  563. // Copy the non-committed state database and check pre/post commit balance
  564. copyOne := state.Copy()
  565. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  566. t.Fatalf("first copy balance mismatch: have %v, want %v", balance, 42)
  567. }
  568. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  569. t.Fatalf("first copy code mismatch: have %x, want %x", code, []byte("hello"))
  570. }
  571. if val := copyOne.GetState(addr, skey); val != sval {
  572. t.Fatalf("first copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  573. }
  574. if val := copyOne.GetCommittedState(addr, skey); val != (common.Hash{}) {
  575. t.Fatalf("first copy committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  576. }
  577. // Copy the copy and check the balance once more
  578. copyTwo := copyOne.Copy()
  579. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  580. t.Fatalf("second copy pre-commit balance mismatch: have %v, want %v", balance, 42)
  581. }
  582. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  583. t.Fatalf("second copy pre-commit code mismatch: have %x, want %x", code, []byte("hello"))
  584. }
  585. if val := copyTwo.GetState(addr, skey); val != sval {
  586. t.Fatalf("second copy pre-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  587. }
  588. if val := copyTwo.GetCommittedState(addr, skey); val != (common.Hash{}) {
  589. t.Fatalf("second copy pre-commit committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  590. }
  591. copyTwo.Finalise(false)
  592. copyTwo.AccountsIntermediateRoot()
  593. copyTwo.Commit(nil)
  594. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  595. t.Fatalf("second copy post-commit balance mismatch: have %v, want %v", balance, 42)
  596. }
  597. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  598. t.Fatalf("second copy post-commit code mismatch: have %x, want %x", code, []byte("hello"))
  599. }
  600. if val := copyTwo.GetState(addr, skey); val != sval {
  601. t.Fatalf("second copy post-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  602. }
  603. if val := copyTwo.GetCommittedState(addr, skey); val != sval {
  604. t.Fatalf("second copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  605. }
  606. // Copy the copy-copy and check the balance once more
  607. copyThree := copyTwo.Copy()
  608. if balance := copyThree.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  609. t.Fatalf("third copy balance mismatch: have %v, want %v", balance, 42)
  610. }
  611. if code := copyThree.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  612. t.Fatalf("third copy code mismatch: have %x, want %x", code, []byte("hello"))
  613. }
  614. if val := copyThree.GetState(addr, skey); val != sval {
  615. t.Fatalf("third copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  616. }
  617. if val := copyThree.GetCommittedState(addr, skey); val != sval {
  618. t.Fatalf("third copy committed storage slot mismatch: have %x, want %x", val, sval)
  619. }
  620. }
  621. // TestDeleteCreateRevert tests a weird state transition corner case that we hit
  622. // while changing the internals of StateDB. The workflow is that a contract is
  623. // self-destructed, then in a follow-up transaction (but same block) it's created
  624. // again and the transaction reverted.
  625. //
  626. // The original StateDB implementation flushed dirty objects to the tries after
  627. // each transaction, so this works ok. The rework accumulated writes in memory
  628. // first, but the journal wiped the entire state object on create-revert.
  629. func TestDeleteCreateRevert(t *testing.T) {
  630. // Create an initial state with a single contract
  631. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  632. addr := common.BytesToAddress([]byte("so"))
  633. state.SetBalance(addr, big.NewInt(1))
  634. state.Finalise(false)
  635. state.AccountsIntermediateRoot()
  636. root, _, _ := state.Commit(nil)
  637. state, _ = New(root, state.db, state.snaps)
  638. // Simulate self-destructing in one transaction, then create-reverting in another
  639. state.Suicide(addr)
  640. state.Finalise(true)
  641. id := state.Snapshot()
  642. state.SetBalance(addr, big.NewInt(2))
  643. state.RevertToSnapshot(id)
  644. state.Finalise(true)
  645. state.AccountsIntermediateRoot()
  646. // Commit the entire state and make sure we don't crash and have the correct state
  647. root, _, _ = state.Commit(nil)
  648. state, _ = New(root, state.db, state.snaps)
  649. if state.getStateObject(addr) != nil {
  650. t.Fatalf("self-destructed contract came alive")
  651. }
  652. }
  653. // TestMissingTrieNodes tests that if the StateDB fails to load parts of the trie,
  654. // the Commit operation fails with an error
  655. // If we are missing trie nodes, we should not continue writing to the trie
  656. func TestMissingTrieNodes(t *testing.T) {
  657. // Create an initial state with a few accounts
  658. memDb := rawdb.NewMemoryDatabase()
  659. db := NewDatabase(memDb)
  660. var root common.Hash
  661. state, _ := New(common.Hash{}, db, nil)
  662. addr := common.BytesToAddress([]byte("so"))
  663. {
  664. state.SetBalance(addr, big.NewInt(1))
  665. state.SetCode(addr, []byte{1, 2, 3})
  666. a2 := common.BytesToAddress([]byte("another"))
  667. state.SetBalance(a2, big.NewInt(100))
  668. state.SetCode(a2, []byte{1, 2, 4})
  669. state.Finalise(false)
  670. state.AccountsIntermediateRoot()
  671. root, _, _ = state.Commit(nil)
  672. t.Logf("root: %x", root)
  673. // force-flush
  674. state.Database().TrieDB().Cap(0)
  675. }
  676. // Create a new state on the old root
  677. state, _ = New(root, db, nil)
  678. // Now we clear out the memdb
  679. it := memDb.NewIterator(nil, nil)
  680. for it.Next() {
  681. k := it.Key()
  682. // Leave the root intact
  683. if !bytes.Equal(k, root[:]) {
  684. t.Logf("key: %x", k)
  685. memDb.Delete(k)
  686. }
  687. }
  688. balance := state.GetBalance(addr)
  689. // The removed elem should lead to it returning zero balance
  690. if exp, got := uint64(0), balance.Uint64(); got != exp {
  691. t.Errorf("expected %d, got %d", exp, got)
  692. }
  693. // Modify the state
  694. state.SetBalance(addr, big.NewInt(2))
  695. state.Finalise(false)
  696. state.AccountsIntermediateRoot()
  697. root, _, err := state.Commit(nil)
  698. if err == nil {
  699. t.Fatalf("expected error, got root :%x", root)
  700. }
  701. }
  702. func TestStateDBAccessList(t *testing.T) {
  703. // Some helpers
  704. addr := func(a string) common.Address {
  705. return common.HexToAddress(a)
  706. }
  707. slot := func(a string) common.Hash {
  708. return common.HexToHash(a)
  709. }
  710. memDb := rawdb.NewMemoryDatabase()
  711. db := NewDatabase(memDb)
  712. state, _ := New(common.Hash{}, db, nil)
  713. state.accessList = newAccessList()
  714. verifyAddrs := func(astrings ...string) {
  715. t.Helper()
  716. // convert to common.Address form
  717. var addresses []common.Address
  718. var addressMap = make(map[common.Address]struct{})
  719. for _, astring := range astrings {
  720. address := addr(astring)
  721. addresses = append(addresses, address)
  722. addressMap[address] = struct{}{}
  723. }
  724. // Check that the given addresses are in the access list
  725. for _, address := range addresses {
  726. if !state.AddressInAccessList(address) {
  727. t.Fatalf("expected %x to be in access list", address)
  728. }
  729. }
  730. // Check that only the expected addresses are present in the acesslist
  731. for address := range state.accessList.addresses {
  732. if _, exist := addressMap[address]; !exist {
  733. t.Fatalf("extra address %x in access list", address)
  734. }
  735. }
  736. }
  737. verifySlots := func(addrString string, slotStrings ...string) {
  738. if !state.AddressInAccessList(addr(addrString)) {
  739. t.Fatalf("scope missing address/slots %v", addrString)
  740. }
  741. var address = addr(addrString)
  742. // convert to common.Hash form
  743. var slots []common.Hash
  744. var slotMap = make(map[common.Hash]struct{})
  745. for _, slotString := range slotStrings {
  746. s := slot(slotString)
  747. slots = append(slots, s)
  748. slotMap[s] = struct{}{}
  749. }
  750. // Check that the expected items are in the access list
  751. for i, s := range slots {
  752. if _, slotPresent := state.SlotInAccessList(address, s); !slotPresent {
  753. t.Fatalf("input %d: scope missing slot %v (address %v)", i, s, addrString)
  754. }
  755. }
  756. // Check that no extra elements are in the access list
  757. index := state.accessList.addresses[address]
  758. if index >= 0 {
  759. stateSlots := state.accessList.slots[index]
  760. for s := range stateSlots {
  761. if _, slotPresent := slotMap[s]; !slotPresent {
  762. t.Fatalf("scope has extra slot %v (address %v)", s, addrString)
  763. }
  764. }
  765. }
  766. }
  767. state.AddAddressToAccessList(addr("aa")) // 1
  768. state.AddSlotToAccessList(addr("bb"), slot("01")) // 2,3
  769. state.AddSlotToAccessList(addr("bb"), slot("02")) // 4
  770. verifyAddrs("aa", "bb")
  771. verifySlots("bb", "01", "02")
  772. // Make a copy
  773. stateCopy1 := state.Copy()
  774. if exp, got := 4, state.journal.length(); exp != got {
  775. t.Fatalf("journal length mismatch: have %d, want %d", got, exp)
  776. }
  777. // same again, should cause no journal entries
  778. state.AddSlotToAccessList(addr("bb"), slot("01"))
  779. state.AddSlotToAccessList(addr("bb"), slot("02"))
  780. state.AddAddressToAccessList(addr("aa"))
  781. if exp, got := 4, state.journal.length(); exp != got {
  782. t.Fatalf("journal length mismatch: have %d, want %d", got, exp)
  783. }
  784. // some new ones
  785. state.AddSlotToAccessList(addr("bb"), slot("03")) // 5
  786. state.AddSlotToAccessList(addr("aa"), slot("01")) // 6
  787. state.AddSlotToAccessList(addr("cc"), slot("01")) // 7,8
  788. state.AddAddressToAccessList(addr("cc"))
  789. if exp, got := 8, state.journal.length(); exp != got {
  790. t.Fatalf("journal length mismatch: have %d, want %d", got, exp)
  791. }
  792. verifyAddrs("aa", "bb", "cc")
  793. verifySlots("aa", "01")
  794. verifySlots("bb", "01", "02", "03")
  795. verifySlots("cc", "01")
  796. // now start rolling back changes
  797. state.journal.revert(state, 7)
  798. if _, ok := state.SlotInAccessList(addr("cc"), slot("01")); ok {
  799. t.Fatalf("slot present, expected missing")
  800. }
  801. verifyAddrs("aa", "bb", "cc")
  802. verifySlots("aa", "01")
  803. verifySlots("bb", "01", "02", "03")
  804. state.journal.revert(state, 6)
  805. if state.AddressInAccessList(addr("cc")) {
  806. t.Fatalf("addr present, expected missing")
  807. }
  808. verifyAddrs("aa", "bb")
  809. verifySlots("aa", "01")
  810. verifySlots("bb", "01", "02", "03")
  811. state.journal.revert(state, 5)
  812. if _, ok := state.SlotInAccessList(addr("aa"), slot("01")); ok {
  813. t.Fatalf("slot present, expected missing")
  814. }
  815. verifyAddrs("aa", "bb")
  816. verifySlots("bb", "01", "02", "03")
  817. state.journal.revert(state, 4)
  818. if _, ok := state.SlotInAccessList(addr("bb"), slot("03")); ok {
  819. t.Fatalf("slot present, expected missing")
  820. }
  821. verifyAddrs("aa", "bb")
  822. verifySlots("bb", "01", "02")
  823. state.journal.revert(state, 3)
  824. if _, ok := state.SlotInAccessList(addr("bb"), slot("02")); ok {
  825. t.Fatalf("slot present, expected missing")
  826. }
  827. verifyAddrs("aa", "bb")
  828. verifySlots("bb", "01")
  829. state.journal.revert(state, 2)
  830. if _, ok := state.SlotInAccessList(addr("bb"), slot("01")); ok {
  831. t.Fatalf("slot present, expected missing")
  832. }
  833. verifyAddrs("aa", "bb")
  834. state.journal.revert(state, 1)
  835. if state.AddressInAccessList(addr("bb")) {
  836. t.Fatalf("addr present, expected missing")
  837. }
  838. verifyAddrs("aa")
  839. state.journal.revert(state, 0)
  840. if state.AddressInAccessList(addr("aa")) {
  841. t.Fatalf("addr present, expected missing")
  842. }
  843. if got, exp := len(state.accessList.addresses), 0; got != exp {
  844. t.Fatalf("expected empty, got %d", got)
  845. }
  846. if got, exp := len(state.accessList.slots), 0; got != exp {
  847. t.Fatalf("expected empty, got %d", got)
  848. }
  849. // Check the copy
  850. // Make a copy
  851. state = stateCopy1
  852. verifyAddrs("aa", "bb")
  853. verifySlots("bb", "01", "02")
  854. if got, exp := len(state.accessList.addresses), 2; got != exp {
  855. t.Fatalf("expected empty, got %d", got)
  856. }
  857. if got, exp := len(state.accessList.slots), 1; got != exp {
  858. t.Fatalf("expected empty, got %d", got)
  859. }
  860. }