snapshot_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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"), 1); err != nil {
  153. t.Fatalf("failed to merge accumulator 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 retains the bottom diff
  169. // layer to check the usual mode of operation where the accumulator is retained.
  170. func TestDiffLayerExternalInvalidationPartialFlatten(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 three 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 err := snaps.Update(common.HexToHash("0x04"), common.HexToHash("0x03"), nil, accounts, nil); err != nil {
  193. t.Fatalf("failed to create a diff layer: %v", err)
  194. }
  195. if n := len(snaps.layers); n != 4 {
  196. t.Errorf("pre-cap layer count mismatch: have %d, want %d", n, 4)
  197. }
  198. ref := snaps.Snapshot(common.HexToHash("0x02"))
  199. // Doing a Cap operation with many allowed layers should be a no-op
  200. exp := len(snaps.layers)
  201. if err := snaps.Cap(common.HexToHash("0x04"), 2000); err != nil {
  202. t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
  203. }
  204. if got := len(snaps.layers); got != exp {
  205. t.Errorf("layers modified, got %d exp %d", got, exp)
  206. }
  207. // Flatten the diff layer into the bottom accumulator
  208. if err := snaps.Cap(common.HexToHash("0x04"), 1); err != nil {
  209. t.Fatalf("failed to flatten diff layer into accumulator: %v", err)
  210. }
  211. // Since the accumulator diff layer was modified, ensure that data retrievald on the external reference fail
  212. if acc, err := ref.Account(common.HexToHash("0x01")); err != ErrSnapshotStale {
  213. t.Errorf("stale reference returned account: %#x (err: %v)", acc, err)
  214. }
  215. if slot, err := ref.Storage(common.HexToHash("0xa1"), common.HexToHash("0xb1")); err != ErrSnapshotStale {
  216. t.Errorf("stale reference returned storage slot: %#x (err: %v)", slot, err)
  217. }
  218. if n := len(snaps.layers); n != 3 {
  219. t.Errorf("post-cap layer count mismatch: have %d, want %d", n, 3)
  220. fmt.Println(snaps.layers)
  221. }
  222. }
  223. // TestPostCapBasicDataAccess tests some functionality regarding capping/flattening.
  224. func TestPostCapBasicDataAccess(t *testing.T) {
  225. // setAccount is a helper to construct a random account entry and assign it to
  226. // an account slot in a snapshot
  227. setAccount := func(accKey string) map[common.Hash][]byte {
  228. return map[common.Hash][]byte{
  229. common.HexToHash(accKey): randomAccount(),
  230. }
  231. }
  232. // Create a starting base layer and a snapshot tree out of it
  233. base := &diskLayer{
  234. diskdb: rawdb.NewMemoryDatabase(),
  235. root: common.HexToHash("0x01"),
  236. cache: fastcache.New(1024 * 500),
  237. }
  238. snaps := &Tree{
  239. layers: map[common.Hash]snapshot{
  240. base.root: base,
  241. },
  242. }
  243. // The lowest difflayer
  244. snaps.Update(common.HexToHash("0xa1"), common.HexToHash("0x01"), nil, setAccount("0xa1"), nil)
  245. snaps.Update(common.HexToHash("0xa2"), common.HexToHash("0xa1"), nil, setAccount("0xa2"), nil)
  246. snaps.Update(common.HexToHash("0xb2"), common.HexToHash("0xa1"), nil, setAccount("0xb2"), nil)
  247. snaps.Update(common.HexToHash("0xa3"), common.HexToHash("0xa2"), nil, setAccount("0xa3"), nil)
  248. snaps.Update(common.HexToHash("0xb3"), common.HexToHash("0xb2"), nil, setAccount("0xb3"), nil)
  249. // checkExist verifies if an account exiss in a snapshot
  250. checkExist := func(layer *diffLayer, key string) error {
  251. if data, _ := layer.Account(common.HexToHash(key)); data == nil {
  252. return fmt.Errorf("expected %x to exist, got nil", common.HexToHash(key))
  253. }
  254. return nil
  255. }
  256. // shouldErr checks that an account access errors as expected
  257. shouldErr := func(layer *diffLayer, key string) error {
  258. if data, err := layer.Account(common.HexToHash(key)); err == nil {
  259. return fmt.Errorf("expected error, got data %x", data)
  260. }
  261. return nil
  262. }
  263. // check basics
  264. snap := snaps.Snapshot(common.HexToHash("0xb3")).(*diffLayer)
  265. if err := checkExist(snap, "0xa1"); err != nil {
  266. t.Error(err)
  267. }
  268. if err := checkExist(snap, "0xb2"); err != nil {
  269. t.Error(err)
  270. }
  271. if err := checkExist(snap, "0xb3"); err != nil {
  272. t.Error(err)
  273. }
  274. // Cap to a bad root should fail
  275. if err := snaps.Cap(common.HexToHash("0x1337"), 0); err == nil {
  276. t.Errorf("expected error, got none")
  277. }
  278. // Now, merge the a-chain
  279. snaps.Cap(common.HexToHash("0xa3"), 0)
  280. // At this point, a2 got merged into a1. Thus, a1 is now modified, and as a1 is
  281. // the parent of b2, b2 should no longer be able to iterate into parent.
  282. // These should still be accessible
  283. if err := checkExist(snap, "0xb2"); err != nil {
  284. t.Error(err)
  285. }
  286. if err := checkExist(snap, "0xb3"); err != nil {
  287. t.Error(err)
  288. }
  289. // But these would need iteration into the modified parent
  290. if err := shouldErr(snap, "0xa1"); err != nil {
  291. t.Error(err)
  292. }
  293. if err := shouldErr(snap, "0xa2"); err != nil {
  294. t.Error(err)
  295. }
  296. if err := shouldErr(snap, "0xa3"); err != nil {
  297. t.Error(err)
  298. }
  299. // Now, merge it again, just for fun. It should now error, since a3
  300. // is a disk layer
  301. if err := snaps.Cap(common.HexToHash("0xa3"), 0); err == nil {
  302. t.Error("expected error capping the disk layer, got none")
  303. }
  304. }
  305. // TestSnaphots tests the functionality for retrieveing the snapshot
  306. // with given head root and the desired depth.
  307. func TestSnaphots(t *testing.T) {
  308. // setAccount is a helper to construct a random account entry and assign it to
  309. // an account slot in a snapshot
  310. setAccount := func(accKey string) map[common.Hash][]byte {
  311. return map[common.Hash][]byte{
  312. common.HexToHash(accKey): randomAccount(),
  313. }
  314. }
  315. makeRoot := func(height uint64) common.Hash {
  316. var buffer [8]byte
  317. binary.BigEndian.PutUint64(buffer[:], height)
  318. return common.BytesToHash(buffer[:])
  319. }
  320. // Create a starting base layer and a snapshot tree out of it
  321. base := &diskLayer{
  322. diskdb: rawdb.NewMemoryDatabase(),
  323. root: makeRoot(1),
  324. cache: fastcache.New(1024 * 500),
  325. }
  326. snaps := &Tree{
  327. layers: map[common.Hash]snapshot{
  328. base.root: base,
  329. },
  330. }
  331. // Construct the snapshots with 129 layers, flattening whatever's above that
  332. var (
  333. last = common.HexToHash("0x01")
  334. head common.Hash
  335. )
  336. for i := 0; i < 129; i++ {
  337. head = makeRoot(uint64(i + 2))
  338. snaps.Update(head, last, nil, setAccount(fmt.Sprintf("%d", i+2)), nil)
  339. last = head
  340. snaps.Cap(head, 128) // 130 layers (128 diffs + 1 accumulator + 1 disk)
  341. }
  342. var cases = []struct {
  343. headRoot common.Hash
  344. limit int
  345. nodisk bool
  346. expected int
  347. expectBottom common.Hash
  348. }{
  349. {head, 0, false, 0, common.Hash{}},
  350. {head, 64, false, 64, makeRoot(129 + 2 - 64)},
  351. {head, 128, false, 128, makeRoot(3)}, // Normal diff layers, no accumulator
  352. {head, 129, true, 129, makeRoot(2)}, // All diff layers, including accumulator
  353. {head, 130, false, 130, makeRoot(1)}, // All diff layers + disk layer
  354. }
  355. for i, c := range cases {
  356. layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
  357. if len(layers) != c.expected {
  358. t.Errorf("non-overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
  359. }
  360. if len(layers) == 0 {
  361. continue
  362. }
  363. bottommost := layers[len(layers)-1]
  364. if bottommost.Root() != c.expectBottom {
  365. t.Errorf("non-overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
  366. }
  367. }
  368. // Above we've tested the normal capping, which leaves the accumulator live.
  369. // Test that if the bottommost accumulator diff layer overflows the allowed
  370. // memory limit, the snapshot tree gets capped to one less layer.
  371. // Commit the diff layer onto the disk and ensure it's persisted
  372. defer func(memcap uint64) { aggregatorMemoryLimit = memcap }(aggregatorMemoryLimit)
  373. aggregatorMemoryLimit = 0
  374. snaps.Cap(head, 128) // 129 (128 diffs + 1 overflown accumulator + 1 disk)
  375. cases = []struct {
  376. headRoot common.Hash
  377. limit int
  378. nodisk bool
  379. expected int
  380. expectBottom common.Hash
  381. }{
  382. {head, 0, false, 0, common.Hash{}},
  383. {head, 64, false, 64, makeRoot(129 + 2 - 64)},
  384. {head, 128, false, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
  385. {head, 129, true, 128, makeRoot(3)}, // All diff layers, accumulator was flattened
  386. {head, 130, false, 129, makeRoot(2)}, // All diff layers + disk layer
  387. }
  388. for i, c := range cases {
  389. layers := snaps.Snapshots(c.headRoot, c.limit, c.nodisk)
  390. if len(layers) != c.expected {
  391. t.Errorf("overflow test %d: returned snapshot layers are mismatched, want %v, got %v", i, c.expected, len(layers))
  392. }
  393. if len(layers) == 0 {
  394. continue
  395. }
  396. bottommost := layers[len(layers)-1]
  397. if bottommost.Root() != c.expectBottom {
  398. t.Errorf("overflow test %d: snapshot mismatch, want %v, get %v", i, c.expectBottom, bottommost.Root())
  399. }
  400. }
  401. }