snapshot_test.go 16 KB

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