statedb_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  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. sdb, _ := New(common.Hash{}, NewDatabase(rawdb.NewMemoryDatabase()))
  409. addr := common.HexToAddress("aaaa")
  410. sdb.SetBalance(addr, big.NewInt(42))
  411. if got := sdb.Copy().GetBalance(addr).Uint64(); got != 42 {
  412. t.Fatalf("1st copy fail, expected 42, got %v", got)
  413. }
  414. if got := sdb.Copy().Copy().GetBalance(addr).Uint64(); got != 42 {
  415. t.Fatalf("2nd copy fail, expected 42, got %v", got)
  416. }
  417. }