statedb_test.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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); 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. transRoot, err := transState.Commit(false)
  94. if err != nil {
  95. t.Fatalf("failed to commit transition state: %v", err)
  96. }
  97. if err = transState.Database().TrieDB().Commit(transRoot, false); err != nil {
  98. t.Errorf("can not commit trie %v to persistent database", transRoot.Hex())
  99. }
  100. finalRoot, err := finalState.Commit(false)
  101. if err != nil {
  102. t.Fatalf("failed to commit final state: %v", err)
  103. }
  104. if err = finalState.Database().TrieDB().Commit(finalRoot, false); err != nil {
  105. t.Errorf("can not commit trie %v to persistent database", finalRoot.Hex())
  106. }
  107. it := finalDb.NewIterator(nil, nil)
  108. for it.Next() {
  109. key, fvalue := it.Key(), it.Value()
  110. tvalue, err := transDb.Get(key)
  111. if err != nil {
  112. t.Errorf("entry missing from the transition database: %x -> %x", key, fvalue)
  113. }
  114. if !bytes.Equal(fvalue, tvalue) {
  115. t.Errorf("the value associate key %x is mismatch,: %x in transition database ,%x in final database", key, tvalue, fvalue)
  116. }
  117. }
  118. it.Release()
  119. it = transDb.NewIterator(nil, nil)
  120. for it.Next() {
  121. key, tvalue := it.Key(), it.Value()
  122. fvalue, err := finalDb.Get(key)
  123. if err != nil {
  124. t.Errorf("extra entry in the transition database: %x -> %x", key, it.Value())
  125. }
  126. if !bytes.Equal(fvalue, tvalue) {
  127. t.Errorf("the value associate key %x is mismatch,: %x in transition database ,%x in final database", key, tvalue, fvalue)
  128. }
  129. }
  130. }
  131. // TestCopy tests that copying a statedb object indeed makes the original and
  132. // the copy independent of each other. This test is a regression test against
  133. // https://github.com/ethereum/go-ethereum/pull/15549.
  134. func TestCopy(t *testing.T) {
  135. // Create a random state test to copy and modify "independently"
  136. orig, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  137. for i := byte(0); i < 255; i++ {
  138. obj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  139. obj.AddBalance(big.NewInt(int64(i)))
  140. orig.updateStateObject(obj)
  141. }
  142. orig.Finalise(false)
  143. // Copy the state
  144. copy := orig.Copy()
  145. // Copy the copy state
  146. ccopy := copy.Copy()
  147. // modify all in memory
  148. for i := byte(0); i < 255; i++ {
  149. origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  150. copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  151. ccopyObj := ccopy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  152. origObj.AddBalance(big.NewInt(2 * int64(i)))
  153. copyObj.AddBalance(big.NewInt(3 * int64(i)))
  154. ccopyObj.AddBalance(big.NewInt(4 * int64(i)))
  155. orig.updateStateObject(origObj)
  156. copy.updateStateObject(copyObj)
  157. ccopy.updateStateObject(copyObj)
  158. }
  159. // Finalise the changes on all concurrently
  160. finalise := func(wg *sync.WaitGroup, db *StateDB) {
  161. defer wg.Done()
  162. db.Finalise(true)
  163. }
  164. var wg sync.WaitGroup
  165. wg.Add(3)
  166. go finalise(&wg, orig)
  167. go finalise(&wg, copy)
  168. go finalise(&wg, ccopy)
  169. wg.Wait()
  170. // Verify that the three states have been updated independently
  171. for i := byte(0); i < 255; i++ {
  172. origObj := orig.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  173. copyObj := copy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  174. ccopyObj := ccopy.GetOrNewStateObject(common.BytesToAddress([]byte{i}))
  175. if want := big.NewInt(3 * int64(i)); origObj.Balance().Cmp(want) != 0 {
  176. t.Errorf("orig obj %d: balance mismatch: have %v, want %v", i, origObj.Balance(), want)
  177. }
  178. if want := big.NewInt(4 * int64(i)); copyObj.Balance().Cmp(want) != 0 {
  179. t.Errorf("copy obj %d: balance mismatch: have %v, want %v", i, copyObj.Balance(), want)
  180. }
  181. if want := big.NewInt(5 * int64(i)); ccopyObj.Balance().Cmp(want) != 0 {
  182. t.Errorf("copy obj %d: balance mismatch: have %v, want %v", i, ccopyObj.Balance(), want)
  183. }
  184. }
  185. }
  186. func TestSnapshotRandom(t *testing.T) {
  187. config := &quick.Config{MaxCount: 1000}
  188. err := quick.Check((*snapshotTest).run, config)
  189. if cerr, ok := err.(*quick.CheckError); ok {
  190. test := cerr.In[0].(*snapshotTest)
  191. t.Errorf("%v:\n%s", test.err, test)
  192. } else if err != nil {
  193. t.Error(err)
  194. }
  195. }
  196. // A snapshotTest checks that reverting StateDB snapshots properly undoes all changes
  197. // captured by the snapshot. Instances of this test with pseudorandom content are created
  198. // by Generate.
  199. //
  200. // The test works as follows:
  201. //
  202. // A new state is created and all actions are applied to it. Several snapshots are taken
  203. // in between actions. The test then reverts each snapshot. For each snapshot the actions
  204. // leading up to it are replayed on a fresh, empty state. The behaviour of all public
  205. // accessor methods on the reverted state must match the return value of the equivalent
  206. // methods on the replayed state.
  207. type snapshotTest struct {
  208. addrs []common.Address // all account addresses
  209. actions []testAction // modifications to the state
  210. snapshots []int // actions indexes at which snapshot is taken
  211. err error // failure details are reported through this field
  212. }
  213. type testAction struct {
  214. name string
  215. fn func(testAction, *StateDB)
  216. args []int64
  217. noAddr bool
  218. }
  219. // newTestAction creates a random action that changes state.
  220. func newTestAction(addr common.Address, r *rand.Rand) testAction {
  221. actions := []testAction{
  222. {
  223. name: "SetBalance",
  224. fn: func(a testAction, s *StateDB) {
  225. s.SetBalance(addr, big.NewInt(a.args[0]))
  226. },
  227. args: make([]int64, 1),
  228. },
  229. {
  230. name: "AddBalance",
  231. fn: func(a testAction, s *StateDB) {
  232. s.AddBalance(addr, big.NewInt(a.args[0]))
  233. },
  234. args: make([]int64, 1),
  235. },
  236. {
  237. name: "SetNonce",
  238. fn: func(a testAction, s *StateDB) {
  239. s.SetNonce(addr, uint64(a.args[0]))
  240. },
  241. args: make([]int64, 1),
  242. },
  243. {
  244. name: "SetState",
  245. fn: func(a testAction, s *StateDB) {
  246. var key, val common.Hash
  247. binary.BigEndian.PutUint16(key[:], uint16(a.args[0]))
  248. binary.BigEndian.PutUint16(val[:], uint16(a.args[1]))
  249. s.SetState(addr, key, val)
  250. },
  251. args: make([]int64, 2),
  252. },
  253. {
  254. name: "SetCode",
  255. fn: func(a testAction, s *StateDB) {
  256. code := make([]byte, 16)
  257. binary.BigEndian.PutUint64(code, uint64(a.args[0]))
  258. binary.BigEndian.PutUint64(code[8:], uint64(a.args[1]))
  259. s.SetCode(addr, code)
  260. },
  261. args: make([]int64, 2),
  262. },
  263. {
  264. name: "CreateAccount",
  265. fn: func(a testAction, s *StateDB) {
  266. s.CreateAccount(addr)
  267. },
  268. },
  269. {
  270. name: "Suicide",
  271. fn: func(a testAction, s *StateDB) {
  272. s.Suicide(addr)
  273. },
  274. },
  275. {
  276. name: "AddRefund",
  277. fn: func(a testAction, s *StateDB) {
  278. s.AddRefund(uint64(a.args[0]))
  279. },
  280. args: make([]int64, 1),
  281. noAddr: true,
  282. },
  283. {
  284. name: "AddLog",
  285. fn: func(a testAction, s *StateDB) {
  286. data := make([]byte, 2)
  287. binary.BigEndian.PutUint16(data, uint16(a.args[0]))
  288. s.AddLog(&types.Log{Address: addr, Data: data})
  289. },
  290. args: make([]int64, 1),
  291. },
  292. {
  293. name: "AddPreimage",
  294. fn: func(a testAction, s *StateDB) {
  295. preimage := []byte{1}
  296. hash := common.BytesToHash(preimage)
  297. s.AddPreimage(hash, preimage)
  298. },
  299. args: make([]int64, 1),
  300. },
  301. }
  302. action := actions[r.Intn(len(actions))]
  303. var nameargs []string
  304. if !action.noAddr {
  305. nameargs = append(nameargs, addr.Hex())
  306. }
  307. for i := range action.args {
  308. action.args[i] = rand.Int63n(100)
  309. nameargs = append(nameargs, fmt.Sprint(action.args[i]))
  310. }
  311. action.name += strings.Join(nameargs, ", ")
  312. return action
  313. }
  314. // Generate returns a new snapshot test of the given size. All randomness is
  315. // derived from r.
  316. func (*snapshotTest) Generate(r *rand.Rand, size int) reflect.Value {
  317. // Generate random actions.
  318. addrs := make([]common.Address, 50)
  319. for i := range addrs {
  320. addrs[i][0] = byte(i)
  321. }
  322. actions := make([]testAction, size)
  323. for i := range actions {
  324. addr := addrs[r.Intn(len(addrs))]
  325. actions[i] = newTestAction(addr, r)
  326. }
  327. // Generate snapshot indexes.
  328. nsnapshots := int(math.Sqrt(float64(size)))
  329. if size > 0 && nsnapshots == 0 {
  330. nsnapshots = 1
  331. }
  332. snapshots := make([]int, nsnapshots)
  333. snaplen := len(actions) / nsnapshots
  334. for i := range snapshots {
  335. // Try to place the snapshots some number of actions apart from each other.
  336. snapshots[i] = (i * snaplen) + r.Intn(snaplen)
  337. }
  338. return reflect.ValueOf(&snapshotTest{addrs, actions, snapshots, nil})
  339. }
  340. func (test *snapshotTest) String() string {
  341. out := new(bytes.Buffer)
  342. sindex := 0
  343. for i, action := range test.actions {
  344. if len(test.snapshots) > sindex && i == test.snapshots[sindex] {
  345. fmt.Fprintf(out, "---- snapshot %d ----\n", sindex)
  346. sindex++
  347. }
  348. fmt.Fprintf(out, "%4d: %s\n", i, action.name)
  349. }
  350. return out.String()
  351. }
  352. func (test *snapshotTest) run() bool {
  353. // Run all actions and create snapshots.
  354. var (
  355. state, _ = New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  356. snapshotRevs = make([]int, len(test.snapshots))
  357. sindex = 0
  358. )
  359. for i, action := range test.actions {
  360. if len(test.snapshots) > sindex && i == test.snapshots[sindex] {
  361. snapshotRevs[sindex] = state.Snapshot()
  362. sindex++
  363. }
  364. action.fn(action, state)
  365. }
  366. // Revert all snapshots in reverse order. Each revert must yield a state
  367. // that is equivalent to fresh state with all actions up the snapshot applied.
  368. for sindex--; sindex >= 0; sindex-- {
  369. checkstate, _ := New(common.Hash{}, state.Database(), nil)
  370. for _, action := range test.actions[:test.snapshots[sindex]] {
  371. action.fn(action, checkstate)
  372. }
  373. state.RevertToSnapshot(snapshotRevs[sindex])
  374. if err := test.checkEqual(state, checkstate); err != nil {
  375. test.err = fmt.Errorf("state mismatch after revert to snapshot %d\n%v", sindex, err)
  376. return false
  377. }
  378. }
  379. return true
  380. }
  381. // checkEqual checks that methods of state and checkstate return the same values.
  382. func (test *snapshotTest) checkEqual(state, checkstate *StateDB) error {
  383. for _, addr := range test.addrs {
  384. var err error
  385. checkeq := func(op string, a, b interface{}) bool {
  386. if err == nil && !reflect.DeepEqual(a, b) {
  387. err = fmt.Errorf("got %s(%s) == %v, want %v", op, addr.Hex(), a, b)
  388. return false
  389. }
  390. return true
  391. }
  392. // Check basic accessor methods.
  393. checkeq("Exist", state.Exist(addr), checkstate.Exist(addr))
  394. checkeq("HasSuicided", state.HasSuicided(addr), checkstate.HasSuicided(addr))
  395. checkeq("GetBalance", state.GetBalance(addr), checkstate.GetBalance(addr))
  396. checkeq("GetNonce", state.GetNonce(addr), checkstate.GetNonce(addr))
  397. checkeq("GetCode", state.GetCode(addr), checkstate.GetCode(addr))
  398. checkeq("GetCodeHash", state.GetCodeHash(addr), checkstate.GetCodeHash(addr))
  399. checkeq("GetCodeSize", state.GetCodeSize(addr), checkstate.GetCodeSize(addr))
  400. // Check storage.
  401. if obj := state.getStateObject(addr); obj != nil {
  402. state.ForEachStorage(addr, func(key, value common.Hash) bool {
  403. return checkeq("GetState("+key.Hex()+")", checkstate.GetState(addr, key), value)
  404. })
  405. checkstate.ForEachStorage(addr, func(key, value common.Hash) bool {
  406. return checkeq("GetState("+key.Hex()+")", checkstate.GetState(addr, key), value)
  407. })
  408. }
  409. if err != nil {
  410. return err
  411. }
  412. }
  413. if state.GetRefund() != checkstate.GetRefund() {
  414. return fmt.Errorf("got GetRefund() == %d, want GetRefund() == %d",
  415. state.GetRefund(), checkstate.GetRefund())
  416. }
  417. if !reflect.DeepEqual(state.GetLogs(common.Hash{}), checkstate.GetLogs(common.Hash{})) {
  418. return fmt.Errorf("got GetLogs(common.Hash{}) == %v, want GetLogs(common.Hash{}) == %v",
  419. state.GetLogs(common.Hash{}), checkstate.GetLogs(common.Hash{}))
  420. }
  421. return nil
  422. }
  423. func TestTouchDelete(t *testing.T) {
  424. s := newStateTest()
  425. s.state.GetOrNewStateObject(common.Address{})
  426. root, _ := s.state.Commit(false)
  427. s.state.Reset(root)
  428. snapshot := s.state.Snapshot()
  429. s.state.AddBalance(common.Address{}, new(big.Int))
  430. if len(s.state.journal.dirties) != 1 {
  431. t.Fatal("expected one dirty state object")
  432. }
  433. s.state.RevertToSnapshot(snapshot)
  434. if len(s.state.journal.dirties) != 0 {
  435. t.Fatal("expected no dirty state object")
  436. }
  437. }
  438. // TestCopyOfCopy tests that modified objects are carried over to the copy, and the copy of the copy.
  439. // See https://github.com/ethereum/go-ethereum/pull/15225#issuecomment-380191512
  440. func TestCopyOfCopy(t *testing.T) {
  441. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  442. addr := common.HexToAddress("aaaa")
  443. state.SetBalance(addr, big.NewInt(42))
  444. if got := state.Copy().GetBalance(addr).Uint64(); got != 42 {
  445. t.Fatalf("1st copy fail, expected 42, got %v", got)
  446. }
  447. if got := state.Copy().Copy().GetBalance(addr).Uint64(); got != 42 {
  448. t.Fatalf("2nd copy fail, expected 42, got %v", got)
  449. }
  450. }
  451. // Tests a regression where committing a copy lost some internal meta information,
  452. // leading to corrupted subsequent copies.
  453. //
  454. // See https://github.com/ethereum/go-ethereum/issues/20106.
  455. func TestCopyCommitCopy(t *testing.T) {
  456. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  457. // Create an account and check if the retrieved balance is correct
  458. addr := common.HexToAddress("0xaffeaffeaffeaffeaffeaffeaffeaffeaffeaffe")
  459. skey := common.HexToHash("aaa")
  460. sval := common.HexToHash("bbb")
  461. state.SetBalance(addr, big.NewInt(42)) // Change the account trie
  462. state.SetCode(addr, []byte("hello")) // Change an external metadata
  463. state.SetState(addr, skey, sval) // Change the storage trie
  464. if balance := state.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  465. t.Fatalf("initial balance mismatch: have %v, want %v", balance, 42)
  466. }
  467. if code := state.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  468. t.Fatalf("initial code mismatch: have %x, want %x", code, []byte("hello"))
  469. }
  470. if val := state.GetState(addr, skey); val != sval {
  471. t.Fatalf("initial non-committed storage slot mismatch: have %x, want %x", val, sval)
  472. }
  473. if val := state.GetCommittedState(addr, skey); val != (common.Hash{}) {
  474. t.Fatalf("initial committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  475. }
  476. // Copy the non-committed state database and check pre/post commit balance
  477. copyOne := state.Copy()
  478. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  479. t.Fatalf("first copy pre-commit balance mismatch: have %v, want %v", balance, 42)
  480. }
  481. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  482. t.Fatalf("first copy pre-commit code mismatch: have %x, want %x", code, []byte("hello"))
  483. }
  484. if val := copyOne.GetState(addr, skey); val != sval {
  485. t.Fatalf("first copy pre-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  486. }
  487. if val := copyOne.GetCommittedState(addr, skey); val != (common.Hash{}) {
  488. t.Fatalf("first copy pre-commit committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  489. }
  490. copyOne.Commit(false)
  491. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  492. t.Fatalf("first copy post-commit balance mismatch: have %v, want %v", balance, 42)
  493. }
  494. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  495. t.Fatalf("first copy post-commit code mismatch: have %x, want %x", code, []byte("hello"))
  496. }
  497. if val := copyOne.GetState(addr, skey); val != sval {
  498. t.Fatalf("first copy post-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  499. }
  500. if val := copyOne.GetCommittedState(addr, skey); val != sval {
  501. t.Fatalf("first copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  502. }
  503. // Copy the copy and check the balance once more
  504. copyTwo := copyOne.Copy()
  505. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  506. t.Fatalf("second copy balance mismatch: have %v, want %v", balance, 42)
  507. }
  508. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  509. t.Fatalf("second copy code mismatch: have %x, want %x", code, []byte("hello"))
  510. }
  511. if val := copyTwo.GetState(addr, skey); val != sval {
  512. t.Fatalf("second copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  513. }
  514. if val := copyTwo.GetCommittedState(addr, skey); val != sval {
  515. t.Fatalf("second copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  516. }
  517. }
  518. // Tests a regression where committing a copy lost some internal meta information,
  519. // leading to corrupted subsequent copies.
  520. //
  521. // See https://github.com/ethereum/go-ethereum/issues/20106.
  522. func TestCopyCopyCommitCopy(t *testing.T) {
  523. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  524. // Create an account and check if the retrieved balance is correct
  525. addr := common.HexToAddress("0xaffeaffeaffeaffeaffeaffeaffeaffeaffeaffe")
  526. skey := common.HexToHash("aaa")
  527. sval := common.HexToHash("bbb")
  528. state.SetBalance(addr, big.NewInt(42)) // Change the account trie
  529. state.SetCode(addr, []byte("hello")) // Change an external metadata
  530. state.SetState(addr, skey, sval) // Change the storage trie
  531. if balance := state.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  532. t.Fatalf("initial balance mismatch: have %v, want %v", balance, 42)
  533. }
  534. if code := state.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  535. t.Fatalf("initial code mismatch: have %x, want %x", code, []byte("hello"))
  536. }
  537. if val := state.GetState(addr, skey); val != sval {
  538. t.Fatalf("initial non-committed storage slot mismatch: have %x, want %x", val, sval)
  539. }
  540. if val := state.GetCommittedState(addr, skey); val != (common.Hash{}) {
  541. t.Fatalf("initial committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  542. }
  543. // Copy the non-committed state database and check pre/post commit balance
  544. copyOne := state.Copy()
  545. if balance := copyOne.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  546. t.Fatalf("first copy balance mismatch: have %v, want %v", balance, 42)
  547. }
  548. if code := copyOne.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  549. t.Fatalf("first copy code mismatch: have %x, want %x", code, []byte("hello"))
  550. }
  551. if val := copyOne.GetState(addr, skey); val != sval {
  552. t.Fatalf("first copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  553. }
  554. if val := copyOne.GetCommittedState(addr, skey); val != (common.Hash{}) {
  555. t.Fatalf("first copy committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  556. }
  557. // Copy the copy and check the balance once more
  558. copyTwo := copyOne.Copy()
  559. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  560. t.Fatalf("second copy pre-commit balance mismatch: have %v, want %v", balance, 42)
  561. }
  562. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  563. t.Fatalf("second copy pre-commit code mismatch: have %x, want %x", code, []byte("hello"))
  564. }
  565. if val := copyTwo.GetState(addr, skey); val != sval {
  566. t.Fatalf("second copy pre-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  567. }
  568. if val := copyTwo.GetCommittedState(addr, skey); val != (common.Hash{}) {
  569. t.Fatalf("second copy pre-commit committed storage slot mismatch: have %x, want %x", val, common.Hash{})
  570. }
  571. copyTwo.Commit(false)
  572. if balance := copyTwo.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  573. t.Fatalf("second copy post-commit balance mismatch: have %v, want %v", balance, 42)
  574. }
  575. if code := copyTwo.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  576. t.Fatalf("second copy post-commit code mismatch: have %x, want %x", code, []byte("hello"))
  577. }
  578. if val := copyTwo.GetState(addr, skey); val != sval {
  579. t.Fatalf("second copy post-commit non-committed storage slot mismatch: have %x, want %x", val, sval)
  580. }
  581. if val := copyTwo.GetCommittedState(addr, skey); val != sval {
  582. t.Fatalf("second copy post-commit committed storage slot mismatch: have %x, want %x", val, sval)
  583. }
  584. // Copy the copy-copy and check the balance once more
  585. copyThree := copyTwo.Copy()
  586. if balance := copyThree.GetBalance(addr); balance.Cmp(big.NewInt(42)) != 0 {
  587. t.Fatalf("third copy balance mismatch: have %v, want %v", balance, 42)
  588. }
  589. if code := copyThree.GetCode(addr); !bytes.Equal(code, []byte("hello")) {
  590. t.Fatalf("third copy code mismatch: have %x, want %x", code, []byte("hello"))
  591. }
  592. if val := copyThree.GetState(addr, skey); val != sval {
  593. t.Fatalf("third copy non-committed storage slot mismatch: have %x, want %x", val, sval)
  594. }
  595. if val := copyThree.GetCommittedState(addr, skey); val != sval {
  596. t.Fatalf("third copy committed storage slot mismatch: have %x, want %x", val, sval)
  597. }
  598. }
  599. // TestDeleteCreateRevert tests a weird state transition corner case that we hit
  600. // while changing the internals of statedb. The workflow is that a contract is
  601. // self destructed, then in a followup transaction (but same block) it's created
  602. // again and the transaction reverted.
  603. //
  604. // The original statedb implementation flushed dirty objects to the tries after
  605. // each transaction, so this works ok. The rework accumulated writes in memory
  606. // first, but the journal wiped the entire state object on create-revert.
  607. func TestDeleteCreateRevert(t *testing.T) {
  608. // Create an initial state with a single contract
  609. state, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()), nil)
  610. addr := toAddr([]byte("so"))
  611. state.SetBalance(addr, big.NewInt(1))
  612. root, _ := state.Commit(false)
  613. state.Reset(root)
  614. // Simulate self-destructing in one transaction, then create-reverting in another
  615. state.Suicide(addr)
  616. state.Finalise(true)
  617. id := state.Snapshot()
  618. state.SetBalance(addr, big.NewInt(2))
  619. state.RevertToSnapshot(id)
  620. // Commit the entire state and make sure we don't crash and have the correct state
  621. root, _ = state.Commit(true)
  622. state.Reset(root)
  623. if state.getStateObject(addr) != nil {
  624. t.Fatalf("self-destructed contract came alive")
  625. }
  626. }