snapshot_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. // Copyright 2017 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. "encoding/binary"
  19. "fmt"
  20. "math/big"
  21. "math/rand"
  22. "testing"
  23. "time"
  24. "github.com/VictoriaMetrics/fastcache"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/rlp"
  28. )
  29. // randomHash generates a random blob of data and returns it as a hash.
  30. func randomHash() common.Hash {
  31. var hash common.Hash
  32. if n, err := rand.Read(hash[:]); n != common.HashLength || err != nil {
  33. panic(err)
  34. }
  35. return hash
  36. }
  37. // randomAccount generates a random account and returns it RLP encoded.
  38. func randomAccount() []byte {
  39. root := randomHash()
  40. a := Account{
  41. Balance: big.NewInt(rand.Int63()),
  42. Nonce: rand.Uint64(),
  43. Root: root[:],
  44. CodeHash: emptyCode[:],
  45. }
  46. data, _ := rlp.EncodeToBytes(a)
  47. return data
  48. }
  49. // randomAccountSet generates a set of random accounts with the given strings as
  50. // the account address hashes.
  51. func randomAccountSet(hashes ...string) map[common.Hash][]byte {
  52. accounts := make(map[common.Hash][]byte)
  53. for _, hash := range hashes {
  54. accounts[common.HexToHash(hash)] = randomAccount()
  55. }
  56. return accounts
  57. }
  58. // randomStorageSet generates a set of random slots with the given strings as
  59. // the slot addresses.
  60. func randomStorageSet(accounts []string, hashes [][]string, nilStorage [][]string) map[common.Hash]map[common.Hash][]byte {
  61. storages := make(map[common.Hash]map[common.Hash][]byte)
  62. for index, account := range accounts {
  63. storages[common.HexToHash(account)] = make(map[common.Hash][]byte)
  64. if index < len(hashes) {
  65. hashes := hashes[index]
  66. for _, hash := range hashes {
  67. storages[common.HexToHash(account)][common.HexToHash(hash)] = randomHash().Bytes()
  68. }
  69. }
  70. if index < len(nilStorage) {
  71. nils := nilStorage[index]
  72. for _, hash := range nils {
  73. storages[common.HexToHash(account)][common.HexToHash(hash)] = nil
  74. }
  75. }
  76. }
  77. return storages
  78. }
  79. // Tests that if a disk layer becomes stale, no active external references will
  80. // be returned with junk data. This version of the test flattens every diff layer
  81. // to check internal corner case around the bottom-most memory accumulator.
  82. func TestDiskLayerExternalInvalidationFullFlatten(t *testing.T) {
  83. // Create an empty base layer and a snapshot tree out of it
  84. base := &diskLayer{
  85. diskdb: rawdb.NewMemoryDatabase(),
  86. root: common.HexToHash("0x01"),
  87. cache: fastcache.New(1024 * 500),
  88. }
  89. snaps := &Tree{
  90. layers: map[common.Hash]snapshot{
  91. base.root: base,
  92. },
  93. }
  94. // Retrieve a reference to the base and commit a diff on top
  95. ref := snaps.Snapshot(base.root)
  96. accounts := map[common.Hash][]byte{
  97. common.HexToHash("0xa1"): randomAccount(),
  98. }
  99. if err := snaps.Update(common.HexToHash("0x02"), common.HexToHash("0x01"), nil, accounts, nil); err != nil {
  100. t.Fatalf("failed to create a diff layer: %v", err)
  101. }
  102. if n := len(snaps.layers); n != 2 {
  103. t.Errorf("pre-cap layer count mismatch: have %d, want %d", n, 2)
  104. }
  105. // Commit the diff layer onto the disk and ensure it's persisted
  106. if err := snaps.Cap(common.HexToHash("0x02"), 0); err != nil {
  107. t.Fatalf("failed to merge diff layer onto disk: %v", err)
  108. }
  109. // Since the base layer was modified, ensure that data retrieval on the external reference fail
  110. if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
  111. t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
  112. }
  113. if slot, err := ref.Storage(common.HexToHash("0xa1"), common.HexToHash("0xb1")); err != ErrSnapshotStale {
  114. t.Errorf("stale reference returned storage slot: %#x (err: %v)", slot, err)
  115. }
  116. if n := len(snaps.layers); n != 1 {
  117. t.Errorf("post-cap layer count mismatch: have %d, want %d", n, 1)
  118. fmt.Println(snaps.layers)
  119. }
  120. }
  121. // Tests that if a disk layer becomes stale, no active external references will
  122. // be returned with junk data. This version of the test retains the bottom diff
  123. // layer to check the usual mode of operation where the accumulator is retained.
  124. func TestDiskLayerExternalInvalidationPartialFlatten(t *testing.T) {
  125. // Create an empty base layer and a snapshot tree out of it
  126. base := &diskLayer{
  127. diskdb: rawdb.NewMemoryDatabase(),
  128. root: common.HexToHash("0x01"),
  129. cache: fastcache.New(1024 * 500),
  130. }
  131. snaps := &Tree{
  132. layers: map[common.Hash]snapshot{
  133. base.root: base,
  134. },
  135. }
  136. // Retrieve a reference to the base and commit two diffs on top
  137. ref := snaps.Snapshot(base.root)
  138. accounts := map[common.Hash][]byte{
  139. common.HexToHash("0xa1"): randomAccount(),
  140. }
  141. if err := snaps.Update(common.HexToHash("0x02"), common.HexToHash("0x01"), nil, accounts, nil); err != nil {
  142. t.Fatalf("failed to create a diff layer: %v", err)
  143. }
  144. if err := snaps.Update(common.HexToHash("0x03"), common.HexToHash("0x02"), nil, accounts, nil); err != nil {
  145. t.Fatalf("failed to create a diff layer: %v", err)
  146. }
  147. if n := len(snaps.layers); n != 3 {
  148. t.Errorf("pre-cap layer count mismatch: have %d, want %d", n, 3)
  149. }
  150. // Commit the diff layer onto the disk and ensure it's persisted
  151. defer func(memcap uint64) { aggregatorMemoryLimit = memcap }(aggregatorMemoryLimit)
  152. aggregatorMemoryLimit = 0
  153. if err := snaps.Cap(common.HexToHash("0x03"), 1); err != nil {
  154. t.Fatalf("failed to merge accumulator onto disk: %v", err)
  155. }
  156. // Since the base layer was modified, ensure that data retrievald on the external reference fail
  157. if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
  158. t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
  159. }
  160. if slot, err := ref.Storage(common.HexToHash("0xa1"), common.HexToHash("0xb1")); err != ErrSnapshotStale {
  161. t.Errorf("stale reference returned storage slot: %#x (err: %v)", slot, err)
  162. }
  163. if n := len(snaps.layers); n != 2 {
  164. t.Errorf("post-cap layer count mismatch: have %d, want %d", n, 2)
  165. fmt.Println(snaps.layers)
  166. }
  167. }
  168. // Tests that if a diff layer becomes stale, no active external references will
  169. // be returned with junk data. This version of the test retains the bottom diff
  170. // layer to check the usual mode of operation where the accumulator is retained.
  171. func TestDiffLayerExternalInvalidationPartialFlatten(t *testing.T) {
  172. // Create an empty base layer and a snapshot tree out of it
  173. base := &diskLayer{
  174. diskdb: rawdb.NewMemoryDatabase(),
  175. root: common.HexToHash("0x01"),
  176. cache: fastcache.New(1024 * 500),
  177. }
  178. snaps := &Tree{
  179. layers: map[common.Hash]snapshot{
  180. base.root: base,
  181. },
  182. }
  183. // Commit three diffs on top and retrieve a reference to the bottommost
  184. accounts := map[common.Hash][]byte{
  185. common.HexToHash("0xa1"): randomAccount(),
  186. }
  187. if err := snaps.Update(common.HexToHash("0x02"), common.HexToHash("0x01"), nil, accounts, nil); err != nil {
  188. t.Fatalf("failed to create a diff layer: %v", err)
  189. }
  190. if err := snaps.Update(common.HexToHash("0x03"), common.HexToHash("0x02"), nil, accounts, nil); err != nil {
  191. t.Fatalf("failed to create a diff layer: %v", err)
  192. }
  193. if err := snaps.Update(common.HexToHash("0x04"), common.HexToHash("0x03"), nil, accounts, nil); err != nil {
  194. t.Fatalf("failed to create a diff layer: %v", err)
  195. }
  196. if n := len(snaps.layers); n != 4 {
  197. t.Errorf("pre-cap layer count mismatch: have %d, want %d", n, 4)
  198. }
  199. ref := snaps.Snapshot(common.HexToHash("0x02"))
  200. // Doing a Cap operation with many allowed layers should be a no-op
  201. exp := len(snaps.layers)
  202. if err := snaps.Cap(common.HexToHash("0x04"), 2000); err != nil {
  203. t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
  204. }
  205. if got := len(snaps.layers); got != exp {
  206. t.Errorf("layers modified, got %d exp %d", got, exp)
  207. }
  208. // Flatten the diff layer into the bottom accumulator
  209. if err := snaps.Cap(common.HexToHash("0x04"), 1); err != nil {
  210. t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
  211. }
  212. // Since the accumulator diff layer was modified, ensure that data retrievald on the external reference fail
  213. if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
  214. t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
  215. }
  216. if slot, err := ref.Storage(common.HexToHash("0xa1"), common.HexToHash("0xb1")); err != ErrSnapshotStale {
  217. t.Errorf("stale reference returned storage slot: %#x (err: %v)", slot, err)
  218. }
  219. if n := len(snaps.layers); n != 3 {
  220. t.Errorf("post-cap layer count mismatch: have %d, want %d", n, 3)
  221. fmt.Println(snaps.layers)
  222. }
  223. }
  224. // TestPostCapBasicDataAccess tests some functionality regarding capping/flattening.
  225. func TestPostCapBasicDataAccess(t *testing.T) {
  226. // setAccount is a helper to construct a random account entry and assign it to
  227. // an account slot in a snapshot
  228. setAccount := func(accKey string) map[common.Hash][]byte {
  229. return map[common.Hash][]byte{
  230. common.HexToHash(accKey): randomAccount(),
  231. }
  232. }
  233. // Create a starting base layer and a snapshot tree out of it
  234. base := &diskLayer{
  235. diskdb: rawdb.NewMemoryDatabase(),
  236. root: common.HexToHash("0x01"),
  237. cache: fastcache.New(1024 * 500),
  238. }
  239. snaps := &Tree{
  240. layers: map[common.Hash]snapshot{
  241. base.root: base,
  242. },
  243. }
  244. // The lowest difflayer
  245. snaps.Update(common.HexToHash("0xa1"), common.HexToHash("0x01"), nil, setAccount("0xa1"), nil)
  246. snaps.Update(common.HexToHash("0xa2"), common.HexToHash("0xa1"), nil, setAccount("0xa2"), nil)
  247. snaps.Update(common.HexToHash("0xb2"), common.HexToHash("0xa1"), nil, setAccount("0xb2"), nil)
  248. snaps.Update(common.HexToHash("0xa3"), common.HexToHash("0xa2"), nil, setAccount("0xa3"), nil)
  249. snaps.Update(common.HexToHash("0xb3"), common.HexToHash("0xb2"), nil, setAccount("0xb3"), nil)
  250. // checkExist verifies if an account exists in a snapshot
  251. checkExist := func(layer *diffLayer, key string) error {
  252. if data, _ := layer.Account(common.HexToHash(key)); data == nil {
  253. return fmt.Errorf("expected %x to exist, got nil", common.HexToHash(key))
  254. }
  255. return nil
  256. }
  257. // shouldErr checks that an account access errors as expected
  258. shouldErr := func(layer *diffLayer, key string) error {
  259. if data, err := layer.Account(common.HexToHash(key)); err == nil {
  260. return fmt.Errorf("expected error, got data %x", data)
  261. }
  262. return nil
  263. }
  264. // check basics
  265. snap := snaps.Snapshot(common.HexToHash("0xb3")).(*diffLayer)
  266. if err := checkExist(snap, "0xa1"); err != nil {
  267. t.Error(err)
  268. }
  269. if err := checkExist(snap, "0xb2"); err != nil {
  270. t.Error(err)
  271. }
  272. if err := checkExist(snap, "0xb3"); err != nil {
  273. t.Error(err)
  274. }
  275. // Cap to a bad root should fail
  276. if err := snaps.Cap(common.HexToHash("0x1337"), 0); err == nil {
  277. t.Errorf("expected error, got none")
  278. }
  279. // Now, merge the a-chain
  280. snaps.Cap(common.HexToHash("0xa3"), 0)
  281. // At this point, a2 got merged into a1. Thus, a1 is now modified, and as a1 is
  282. // the parent of b2, b2 should no longer be able to iterate into parent.
  283. // These should still be accessible
  284. if err := checkExist(snap, "0xb2"); err != nil {
  285. t.Error(err)
  286. }
  287. if err := checkExist(snap, "0xb3"); err != nil {
  288. t.Error(err)
  289. }
  290. // But these would need iteration into the modified parent
  291. if err := shouldErr(snap, "0xa1"); err != nil {
  292. t.Error(err)
  293. }
  294. if err := shouldErr(snap, "0xa2"); err != nil {
  295. t.Error(err)
  296. }
  297. if err := shouldErr(snap, "0xa3"); err != nil {
  298. t.Error(err)
  299. }
  300. // Now, merge it again, just for fun. It should now error, since a3
  301. // is a disk layer
  302. if err := snaps.Cap(common.HexToHash("0xa3"), 0); err == nil {
  303. t.Error("expected error capping the disk layer, got none")
  304. }
  305. }
  306. // TestSnaphots tests the functionality for retrieving the snapshot
  307. // with given head root and the desired depth.
  308. func TestSnaphots(t *testing.T) {
  309. // setAccount is a helper to construct a random account entry and assign it to
  310. // an account slot in a snapshot
  311. setAccount := func(accKey string) map[common.Hash][]byte {
  312. return map[common.Hash][]byte{
  313. common.HexToHash(accKey): randomAccount(),
  314. }
  315. }
  316. makeRoot := func(height uint64) common.Hash {
  317. var buffer [8]byte
  318. binary.BigEndian.PutUint64(buffer[:], height)
  319. return common.BytesToHash(buffer[:])
  320. }
  321. // Create a starting base layer and a snapshot tree out of it
  322. base := &diskLayer{
  323. diskdb: rawdb.NewMemoryDatabase(),
  324. root: makeRoot(1),
  325. cache: fastcache.New(1024 * 500),
  326. }
  327. snaps := &Tree{
  328. layers: map[common.Hash]snapshot{
  329. base.root: base,
  330. },
  331. }
  332. // Construct the snapshots with 129 layers, flattening whatever's above that
  333. var (
  334. last = common.HexToHash("0x01")
  335. head common.Hash
  336. )
  337. for i := 0; i < 129; i++ {
  338. head = makeRoot(uint64(i + 2))
  339. snaps.Update(head, last, nil, setAccount(fmt.Sprintf("%d", i+2)), nil)
  340. last = head
  341. snaps.Cap(head, 128) // 130 layers (128 diffs + 1 accumulator + 1 disk)
  342. }
  343. var cases = []struct {
  344. headRoot common.Hash
  345. limit int
  346. nodisk bool
  347. expected int
  348. expectBottom common.Hash
  349. }{
  350. {head, 0, false, 0, common.Hash{}},
  351. {head, 64, false, 64, makeRoot(129 + 2 - 64)},
  352. {head, 128, false, 128, makeRoot(3)}, // Normal diff layers, no accumulator
  353. {head, 129, true, 129, makeRoot(2)}, // All diff layers, including accumulator
  354. {head, 130, false, 130, makeRoot(1)}, // All diff layers + disk layer
  355. }
  356. for i, c := range cases {
  357. layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
  358. if len(layers) != c.expected {
  359. t.Errorf("non-overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
  360. }
  361. if len(layers) == 0 {
  362. continue
  363. }
  364. bottommost := layers[len(layers)-1]
  365. if bottommost.Root() != c.expectBottom {
  366. t.Errorf("non-overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
  367. }
  368. }
  369. // Above we've tested the normal capping, which leaves the accumulator live.
  370. // Test that if the bottommost accumulator diff layer overflows the allowed
  371. // memory limit, the snapshot tree gets capped to one less layer.
  372. // Commit the diff layer onto the disk and ensure it's persisted
  373. defer func(memcap uint64) { aggregatorMemoryLimit = memcap }(aggregatorMemoryLimit)
  374. aggregatorMemoryLimit = 0
  375. snaps.Cap(head, 128) // 129 (128 diffs + 1 overflown accumulator + 1 disk)
  376. cases = []struct {
  377. headRoot common.Hash
  378. limit int
  379. nodisk bool
  380. expected int
  381. expectBottom common.Hash
  382. }{
  383. {head, 0, false, 0, common.Hash{}},
  384. {head, 64, false, 64, makeRoot(129 + 2 - 64)},
  385. {head, 128, false, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
  386. {head, 129, true, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
  387. {head, 130, false, 129, makeRoot(2)}, // All diff layers + disk layer
  388. }
  389. for i, c := range cases {
  390. layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
  391. if len(layers) != c.expected {
  392. t.Errorf("overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
  393. }
  394. if len(layers) == 0 {
  395. continue
  396. }
  397. bottommost := layers[len(layers)-1]
  398. if bottommost.Root() != c.expectBottom {
  399. t.Errorf("overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
  400. }
  401. }
  402. }
  403. // TestReadStateDuringFlattening tests the scenario that, during the
  404. // bottom diff layers are merging which tags these as stale, the read
  405. // happens via a pre-created top snapshot layer which tries to access
  406. // the state in these stale layers. Ensure this read can retrieve the
  407. // right state back(block until the flattening is finished) instead of
  408. // an unexpected error(snapshot layer is stale).
  409. func TestReadStateDuringFlattening(t *testing.T) {
  410. // setAccount is a helper to construct a random account entry and assign it to
  411. // an account slot in a snapshot
  412. setAccount := func(accKey string) map[common.Hash][]byte {
  413. return map[common.Hash][]byte{
  414. common.HexToHash(accKey): randomAccount(),
  415. }
  416. }
  417. // Create a starting base layer and a snapshot tree out of it
  418. base := &diskLayer{
  419. diskdb: rawdb.NewMemoryDatabase(),
  420. root: common.HexToHash("0x01"),
  421. cache: fastcache.New(1024 * 500),
  422. }
  423. snaps := &Tree{
  424. layers: map[common.Hash]snapshot{
  425. base.root: base,
  426. },
  427. }
  428. // 4 layers in total, 3 diff layers and 1 disk layers
  429. snaps.Update(common.HexToHash("0xa1"), common.HexToHash("0x01"), nil, setAccount("0xa1"), nil)
  430. snaps.Update(common.HexToHash("0xa2"), common.HexToHash("0xa1"), nil, setAccount("0xa2"), nil)
  431. snaps.Update(common.HexToHash("0xa3"), common.HexToHash("0xa2"), nil, setAccount("0xa3"), nil)
  432. // Obtain the topmost snapshot handler for state accessing
  433. snap := snaps.Snapshot(common.HexToHash("0xa3"))
  434. // Register the testing hook to access the state after flattening
  435. var result = make(chan *Account)
  436. snaps.onFlatten = func() {
  437. // Spin up a thread to read the account from the pre-created
  438. // snapshot handler. It's expected to be blocked.
  439. go func() {
  440. account, _ := snap.Account(common.HexToHash("0xa1"))
  441. result <- account
  442. }()
  443. select {
  444. case res := <-result:
  445. t.Fatalf("Unexpected return %v", res)
  446. case <-time.NewTimer(time.Millisecond * 300).C:
  447. }
  448. }
  449. // Cap the snap tree, which will mark the bottom-most layer as stale.
  450. snaps.Cap(common.HexToHash("0xa3"), 1)
  451. select {
  452. case account := <-result:
  453. if account == nil {
  454. t.Fatal("Failed to retrieve account")
  455. }
  456. case <-time.NewTimer(time.Millisecond * 300).C:
  457. t.Fatal("Unexpected blocker")
  458. }
  459. }