difflayer_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. // Copyright 2019 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 snapshot
  17. import (
  18. "bytes"
  19. "fmt"
  20. "math/big"
  21. "math/rand"
  22. "testing"
  23. "time"
  24. "github.com/allegro/bigcache"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. func randomAccount() []byte {
  30. root := randomHash()
  31. a := Account{
  32. Balance: big.NewInt(rand.Int63()),
  33. Nonce: rand.Uint64(),
  34. Root: root[:],
  35. CodeHash: emptyCode[:],
  36. }
  37. data, _ := rlp.EncodeToBytes(a)
  38. return data
  39. }
  40. // TestMergeBasics tests some simple merges
  41. func TestMergeBasics(t *testing.T) {
  42. var (
  43. accounts = make(map[common.Hash][]byte)
  44. storage = make(map[common.Hash]map[common.Hash][]byte)
  45. )
  46. // Fill up a parent
  47. for i := 0; i < 100; i++ {
  48. h := randomHash()
  49. data := randomAccount()
  50. accounts[h] = data
  51. if rand.Intn(20) < 10 {
  52. accStorage := make(map[common.Hash][]byte)
  53. value := make([]byte, 32)
  54. rand.Read(value)
  55. accStorage[randomHash()] = value
  56. storage[h] = accStorage
  57. }
  58. }
  59. // Add some (identical) layers on top
  60. parent := newDiffLayer(emptyLayer{}, 1, common.Hash{}, accounts, storage)
  61. child := newDiffLayer(parent, 1, common.Hash{}, accounts, storage)
  62. child = newDiffLayer(child, 1, common.Hash{}, accounts, storage)
  63. child = newDiffLayer(child, 1, common.Hash{}, accounts, storage)
  64. child = newDiffLayer(child, 1, common.Hash{}, accounts, storage)
  65. // And flatten
  66. merged := (child.flatten()).(*diffLayer)
  67. { // Check account lists
  68. // Should be zero/nil first
  69. if got, exp := len(merged.accountList), 0; got != exp {
  70. t.Errorf("accountList wrong, got %v exp %v", got, exp)
  71. }
  72. // Then set when we call AccountList
  73. if got, exp := len(merged.AccountList()), len(accounts); got != exp {
  74. t.Errorf("AccountList() wrong, got %v exp %v", got, exp)
  75. }
  76. if got, exp := len(merged.accountList), len(accounts); got != exp {
  77. t.Errorf("accountList [2] wrong, got %v exp %v", got, exp)
  78. }
  79. }
  80. { // Check storage lists
  81. i := 0
  82. for aHash, sMap := range storage {
  83. if got, exp := len(merged.storageList), i; got != exp {
  84. t.Errorf("[1] storageList wrong, got %v exp %v", got, exp)
  85. }
  86. if got, exp := len(merged.StorageList(aHash)), len(sMap); got != exp {
  87. t.Errorf("[2] StorageList() wrong, got %v exp %v", got, exp)
  88. }
  89. if got, exp := len(merged.storageList[aHash]), len(sMap); got != exp {
  90. t.Errorf("storageList wrong, got %v exp %v", got, exp)
  91. }
  92. i++
  93. }
  94. }
  95. }
  96. // TestMergeDelete tests some deletion
  97. func TestMergeDelete(t *testing.T) {
  98. var (
  99. storage = make(map[common.Hash]map[common.Hash][]byte)
  100. )
  101. // Fill up a parent
  102. h1 := common.HexToHash("0x01")
  103. h2 := common.HexToHash("0x02")
  104. flip := func() map[common.Hash][]byte {
  105. accs := make(map[common.Hash][]byte)
  106. accs[h1] = randomAccount()
  107. accs[h2] = nil
  108. return accs
  109. }
  110. flop := func() map[common.Hash][]byte {
  111. accs := make(map[common.Hash][]byte)
  112. accs[h1] = nil
  113. accs[h2] = randomAccount()
  114. return accs
  115. }
  116. // Add some flip-flopping layers on top
  117. parent := newDiffLayer(emptyLayer{}, 1, common.Hash{}, flip(), storage)
  118. child := parent.Update(common.Hash{}, flop(), storage)
  119. child = child.Update(common.Hash{}, flip(), storage)
  120. child = child.Update(common.Hash{}, flop(), storage)
  121. child = child.Update(common.Hash{}, flip(), storage)
  122. child = child.Update(common.Hash{}, flop(), storage)
  123. child = child.Update(common.Hash{}, flip(), storage)
  124. if data, _ := child.Account(h1); data == nil {
  125. t.Errorf("last diff layer: expected %x to be non-nil", h1)
  126. }
  127. if data, _ := child.Account(h2); data != nil {
  128. t.Errorf("last diff layer: expected %x to be nil", h2)
  129. }
  130. // And flatten
  131. merged := (child.flatten()).(*diffLayer)
  132. // check number
  133. if got, exp := merged.number, child.number; got != exp {
  134. t.Errorf("merged layer: wrong number - exp %d got %d", exp, got)
  135. }
  136. if data, _ := merged.Account(h1); data == nil {
  137. t.Errorf("merged layer: expected %x to be non-nil", h1)
  138. }
  139. if data, _ := merged.Account(h2); data != nil {
  140. t.Errorf("merged layer: expected %x to be nil", h2)
  141. }
  142. // If we add more granular metering of memory, we can enable this again,
  143. // but it's not implemented for now
  144. //if got, exp := merged.memory, child.memory; got != exp {
  145. // t.Errorf("mem wrong, got %d, exp %d", got, exp)
  146. //}
  147. }
  148. // This tests that if we create a new account, and set a slot, and then merge
  149. // it, the lists will be correct.
  150. func TestInsertAndMerge(t *testing.T) {
  151. // Fill up a parent
  152. var (
  153. acc = common.HexToHash("0x01")
  154. slot = common.HexToHash("0x02")
  155. parent *diffLayer
  156. child *diffLayer
  157. )
  158. {
  159. var accounts = make(map[common.Hash][]byte)
  160. var storage = make(map[common.Hash]map[common.Hash][]byte)
  161. parent = newDiffLayer(emptyLayer{}, 1, common.Hash{}, accounts, storage)
  162. }
  163. {
  164. var accounts = make(map[common.Hash][]byte)
  165. var storage = make(map[common.Hash]map[common.Hash][]byte)
  166. accounts[acc] = randomAccount()
  167. accstorage := make(map[common.Hash][]byte)
  168. storage[acc] = accstorage
  169. storage[acc][slot] = []byte{0x01}
  170. child = newDiffLayer(parent, 2, common.Hash{}, accounts, storage)
  171. }
  172. // And flatten
  173. merged := (child.flatten()).(*diffLayer)
  174. { // Check that slot value is present
  175. got, _ := merged.Storage(acc, slot)
  176. if exp := []byte{0x01}; bytes.Compare(got, exp) != 0 {
  177. t.Errorf("merged slot value wrong, got %x, exp %x", got, exp)
  178. }
  179. }
  180. }
  181. // TestCapTree tests some functionality regarding capping/flattening
  182. func TestCapTree(t *testing.T) {
  183. var (
  184. storage = make(map[common.Hash]map[common.Hash][]byte)
  185. )
  186. setAccount := func(accKey string) map[common.Hash][]byte {
  187. return map[common.Hash][]byte{
  188. common.HexToHash(accKey): randomAccount(),
  189. }
  190. }
  191. // the bottom-most layer, aside from the 'disk layer'
  192. cache, _ := bigcache.NewBigCache(bigcache.Config{ // TODO(karalabe): dedup
  193. Shards: 1,
  194. LifeWindow: time.Hour,
  195. MaxEntriesInWindow: 1 * 1024,
  196. MaxEntrySize: 1,
  197. HardMaxCacheSize: 1,
  198. })
  199. base := &diskLayer{
  200. journal: "",
  201. db: rawdb.NewMemoryDatabase(),
  202. cache: cache,
  203. number: 0,
  204. root: common.HexToHash("0x01"),
  205. }
  206. // The lowest difflayer
  207. a1 := base.Update(common.HexToHash("0xa1"), setAccount("0xa1"), storage)
  208. a2 := a1.Update(common.HexToHash("0xa2"), setAccount("0xa2"), storage)
  209. b2 := a1.Update(common.HexToHash("0xb2"), setAccount("0xb2"), storage)
  210. a3 := a2.Update(common.HexToHash("0xa3"), setAccount("0xa3"), storage)
  211. b3 := b2.Update(common.HexToHash("0xb3"), setAccount("0xb3"), storage)
  212. checkExist := func(layer *diffLayer, key string) error {
  213. accountKey := common.HexToHash(key)
  214. data, _ := layer.Account(accountKey)
  215. if data == nil {
  216. return fmt.Errorf("expected %x to exist, got nil", accountKey)
  217. }
  218. return nil
  219. }
  220. shouldErr := func(layer *diffLayer, key string) error {
  221. accountKey := common.HexToHash(key)
  222. data, err := layer.Account(accountKey)
  223. if err == nil {
  224. return fmt.Errorf("expected error, got data %x", data)
  225. }
  226. return nil
  227. }
  228. // check basics
  229. if err := checkExist(b3, "0xa1"); err != nil {
  230. t.Error(err)
  231. }
  232. if err := checkExist(b3, "0xb2"); err != nil {
  233. t.Error(err)
  234. }
  235. if err := checkExist(b3, "0xb3"); err != nil {
  236. t.Error(err)
  237. }
  238. // Now, merge the a-chain
  239. diskNum, diffNum := a3.Cap(0, 1024)
  240. if diskNum != 0 {
  241. t.Errorf("disk layer err, got %d exp %d", diskNum, 0)
  242. }
  243. if diffNum != 2 {
  244. t.Errorf("diff layer err, got %d exp %d", diffNum, 2)
  245. }
  246. // At this point, a2 got merged into a1. Thus, a1 is now modified,
  247. // and as a1 is the parent of b2, b2 should no longer be able to iterate into parent
  248. // These should still be accessible
  249. if err := checkExist(b3, "0xb2"); err != nil {
  250. t.Error(err)
  251. }
  252. if err := checkExist(b3, "0xb3"); err != nil {
  253. t.Error(err)
  254. }
  255. //b2ParentNum, _ := b2.parent.Info()
  256. //if b2.parent.invalid == false
  257. // t.Errorf("err, exp parent to be invalid, got %v", b2.parent, b2ParentNum)
  258. //}
  259. // But these would need iteration into the modified parent:
  260. if err := shouldErr(b3, "0xa1"); err != nil {
  261. t.Error(err)
  262. }
  263. if err := shouldErr(b3, "0xa2"); err != nil {
  264. t.Error(err)
  265. }
  266. if err := shouldErr(b3, "0xa3"); err != nil {
  267. t.Error(err)
  268. }
  269. }
  270. type emptyLayer struct{}
  271. func (emptyLayer) Update(blockRoot common.Hash, accounts map[common.Hash][]byte, storage map[common.Hash]map[common.Hash][]byte) *diffLayer {
  272. panic("implement me")
  273. }
  274. func (emptyLayer) Cap(layers int, memory uint64) (uint64, uint64) {
  275. panic("implement me")
  276. }
  277. func (emptyLayer) Journal() error {
  278. panic("implement me")
  279. }
  280. func (emptyLayer) Info() (uint64, common.Hash) {
  281. return 0, common.Hash{}
  282. }
  283. func (emptyLayer) Number() uint64 {
  284. return 0
  285. }
  286. func (emptyLayer) Account(hash common.Hash) (*Account, error) {
  287. return nil, nil
  288. }
  289. func (emptyLayer) AccountRLP(hash common.Hash) ([]byte, error) {
  290. return nil, nil
  291. }
  292. func (emptyLayer) Storage(accountHash, storageHash common.Hash) ([]byte, error) {
  293. return nil, nil
  294. }
  295. // BenchmarkSearch checks how long it takes to find a non-existing key
  296. // BenchmarkSearch-6 200000 10481 ns/op (1K per layer)
  297. // BenchmarkSearch-6 200000 10760 ns/op (10K per layer)
  298. // BenchmarkSearch-6 100000 17866 ns/op
  299. //
  300. // BenchmarkSearch-6 500000 3723 ns/op (10k per layer, only top-level RLock()
  301. func BenchmarkSearch(b *testing.B) {
  302. // First, we set up 128 diff layers, with 1K items each
  303. blocknum := uint64(0)
  304. fill := func(parent snapshot) *diffLayer {
  305. accounts := make(map[common.Hash][]byte)
  306. storage := make(map[common.Hash]map[common.Hash][]byte)
  307. for i := 0; i < 10000; i++ {
  308. accounts[randomHash()] = randomAccount()
  309. }
  310. blocknum++
  311. return newDiffLayer(parent, blocknum, common.Hash{}, accounts, storage)
  312. }
  313. var layer snapshot
  314. layer = emptyLayer{}
  315. for i := 0; i < 128; i++ {
  316. layer = fill(layer)
  317. }
  318. key := common.Hash{}
  319. b.ResetTimer()
  320. for i := 0; i < b.N; i++ {
  321. layer.AccountRLP(key)
  322. }
  323. }
  324. // BenchmarkSearchSlot checks how long it takes to find a non-existing key
  325. // - Number of layers: 128
  326. // - Each layers contains the account, with a couple of storage slots
  327. // BenchmarkSearchSlot-6 100000 14554 ns/op
  328. // BenchmarkSearchSlot-6 100000 22254 ns/op (when checking parent root using mutex)
  329. // BenchmarkSearchSlot-6 100000 14551 ns/op (when checking parent number using atomic)
  330. func BenchmarkSearchSlot(b *testing.B) {
  331. // First, we set up 128 diff layers, with 1K items each
  332. blocknum := uint64(0)
  333. accountKey := common.Hash{}
  334. storageKey := common.HexToHash("0x1337")
  335. accountRLP := randomAccount()
  336. fill := func(parent snapshot) *diffLayer {
  337. accounts := make(map[common.Hash][]byte)
  338. accounts[accountKey] = accountRLP
  339. storage := make(map[common.Hash]map[common.Hash][]byte)
  340. accStorage := make(map[common.Hash][]byte)
  341. for i := 0; i < 5; i++ {
  342. value := make([]byte, 32)
  343. rand.Read(value)
  344. accStorage[randomHash()] = value
  345. storage[accountKey] = accStorage
  346. }
  347. blocknum++
  348. return newDiffLayer(parent, blocknum, common.Hash{}, accounts, storage)
  349. }
  350. var layer snapshot
  351. layer = emptyLayer{}
  352. for i := 0; i < 128; i++ {
  353. layer = fill(layer)
  354. }
  355. b.ResetTimer()
  356. for i := 0; i < b.N; i++ {
  357. layer.Storage(accountKey, storageKey)
  358. }
  359. }
  360. // With accountList and sorting
  361. //BenchmarkFlatten-6 50 29890856 ns/op
  362. //
  363. // Without sorting and tracking accountlist
  364. // BenchmarkFlatten-6 300 5511511 ns/op
  365. func BenchmarkFlatten(b *testing.B) {
  366. fill := func(parent snapshot, blocknum int) *diffLayer {
  367. accounts := make(map[common.Hash][]byte)
  368. storage := make(map[common.Hash]map[common.Hash][]byte)
  369. for i := 0; i < 100; i++ {
  370. accountKey := randomHash()
  371. accounts[accountKey] = randomAccount()
  372. accStorage := make(map[common.Hash][]byte)
  373. for i := 0; i < 20; i++ {
  374. value := make([]byte, 32)
  375. rand.Read(value)
  376. accStorage[randomHash()] = value
  377. }
  378. storage[accountKey] = accStorage
  379. }
  380. return newDiffLayer(parent, uint64(blocknum), common.Hash{}, accounts, storage)
  381. }
  382. b.ResetTimer()
  383. for i := 0; i < b.N; i++ {
  384. b.StopTimer()
  385. var layer snapshot
  386. layer = emptyLayer{}
  387. for i := 1; i < 128; i++ {
  388. layer = fill(layer, i)
  389. }
  390. b.StartTimer()
  391. for i := 1; i < 128; i++ {
  392. dl, ok := layer.(*diffLayer)
  393. if !ok {
  394. break
  395. }
  396. layer = dl.flatten()
  397. }
  398. b.StopTimer()
  399. }
  400. }