statedb_test.go 23 KB

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