chain_indexer_test.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  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 core
  17. import (
  18. "context"
  19. "errors"
  20. "fmt"
  21. "math/big"
  22. "math/rand"
  23. "testing"
  24. "time"
  25. "github.com/ethereum/go-ethereum/common"
  26. "github.com/ethereum/go-ethereum/core/rawdb"
  27. "github.com/ethereum/go-ethereum/core/types"
  28. )
  29. // Runs multiple tests with randomized parameters.
  30. func TestChainIndexerSingle(t *testing.T) {
  31. for i := 0; i < 10; i++ {
  32. testChainIndexer(t, 1)
  33. }
  34. }
  35. // Runs multiple tests with randomized parameters and different number of
  36. // chain backends.
  37. func TestChainIndexerWithChildren(t *testing.T) {
  38. for i := 2; i < 8; i++ {
  39. testChainIndexer(t, i)
  40. }
  41. }
  42. // testChainIndexer runs a test with either a single chain indexer or a chain of
  43. // multiple backends. The section size and required confirmation count parameters
  44. // are randomized.
  45. func testChainIndexer(t *testing.T, count int) {
  46. db := rawdb.NewMemoryDatabase()
  47. defer db.Close()
  48. // Create a chain of indexers and ensure they all report empty
  49. backends := make([]*testChainIndexBackend, count)
  50. for i := 0; i < count; i++ {
  51. var (
  52. sectionSize = uint64(rand.Intn(100) + 1)
  53. confirmsReq = uint64(rand.Intn(10))
  54. )
  55. backends[i] = &testChainIndexBackend{t: t, processCh: make(chan uint64)}
  56. backends[i].indexer = NewChainIndexer(db, rawdb.NewTable(db, string([]byte{byte(i)})), backends[i], sectionSize, confirmsReq, 0, fmt.Sprintf("indexer-%d", i))
  57. if sections, _, _ := backends[i].indexer.Sections(); sections != 0 {
  58. t.Fatalf("Canonical section count mismatch: have %v, want %v", sections, 0)
  59. }
  60. if i > 0 {
  61. backends[i-1].indexer.AddChildIndexer(backends[i].indexer)
  62. }
  63. }
  64. defer backends[0].indexer.Close() // parent indexer shuts down children
  65. // notify pings the root indexer about a new head or reorg, then expect
  66. // processed blocks if a section is processable
  67. notify := func(headNum, failNum uint64, reorg bool) {
  68. backends[0].indexer.newHead(headNum, reorg)
  69. if reorg {
  70. for _, backend := range backends {
  71. headNum = backend.reorg(headNum)
  72. backend.assertSections()
  73. }
  74. return
  75. }
  76. var cascade bool
  77. for _, backend := range backends {
  78. headNum, cascade = backend.assertBlocks(headNum, failNum)
  79. if !cascade {
  80. break
  81. }
  82. backend.assertSections()
  83. }
  84. }
  85. // inject inserts a new random canonical header into the database directly
  86. inject := func(number uint64) {
  87. header := &types.Header{Number: big.NewInt(int64(number)), Extra: big.NewInt(rand.Int63()).Bytes()}
  88. if number > 0 {
  89. header.ParentHash = rawdb.ReadCanonicalHash(db, number-1)
  90. }
  91. rawdb.WriteHeader(db, header)
  92. rawdb.WriteCanonicalHash(db, header.Hash(), number)
  93. }
  94. // Start indexer with an already existing chain
  95. for i := uint64(0); i <= 100; i++ {
  96. inject(i)
  97. }
  98. notify(100, 100, false)
  99. // Add new blocks one by one
  100. for i := uint64(101); i <= 1000; i++ {
  101. inject(i)
  102. notify(i, i, false)
  103. }
  104. // Do a reorg
  105. notify(500, 500, true)
  106. // Create new fork
  107. for i := uint64(501); i <= 1000; i++ {
  108. inject(i)
  109. notify(i, i, false)
  110. }
  111. for i := uint64(1001); i <= 1500; i++ {
  112. inject(i)
  113. }
  114. // Failed processing scenario where less blocks are available than notified
  115. notify(2000, 1500, false)
  116. // Notify about a reorg (which could have caused the missing blocks if happened during processing)
  117. notify(1500, 1500, true)
  118. // Create new fork
  119. for i := uint64(1501); i <= 2000; i++ {
  120. inject(i)
  121. notify(i, i, false)
  122. }
  123. }
  124. // testChainIndexBackend implements ChainIndexerBackend
  125. type testChainIndexBackend struct {
  126. t *testing.T
  127. indexer *ChainIndexer
  128. section, headerCnt, stored uint64
  129. processCh chan uint64
  130. }
  131. // assertSections verifies if a chain indexer has the correct number of section.
  132. func (b *testChainIndexBackend) assertSections() {
  133. // Keep trying for 3 seconds if it does not match
  134. var sections uint64
  135. for i := 0; i < 300; i++ {
  136. sections, _, _ = b.indexer.Sections()
  137. if sections == b.stored {
  138. return
  139. }
  140. time.Sleep(10 * time.Millisecond)
  141. }
  142. b.t.Fatalf("Canonical section count mismatch: have %v, want %v", sections, b.stored)
  143. }
  144. // assertBlocks expects processing calls after new blocks have arrived. If the
  145. // failNum < headNum then we are simulating a scenario where a reorg has happened
  146. // after the processing has started and the processing of a section fails.
  147. func (b *testChainIndexBackend) assertBlocks(headNum, failNum uint64) (uint64, bool) {
  148. var sections uint64
  149. if headNum >= b.indexer.confirmsReq {
  150. sections = (headNum + 1 - b.indexer.confirmsReq) / b.indexer.sectionSize
  151. if sections > b.stored {
  152. // expect processed blocks
  153. for expectd := b.stored * b.indexer.sectionSize; expectd < sections*b.indexer.sectionSize; expectd++ {
  154. if expectd > failNum {
  155. // rolled back after processing started, no more process calls expected
  156. // wait until updating is done to make sure that processing actually fails
  157. var updating bool
  158. for i := 0; i < 300; i++ {
  159. b.indexer.lock.Lock()
  160. updating = b.indexer.knownSections > b.indexer.storedSections
  161. b.indexer.lock.Unlock()
  162. if !updating {
  163. break
  164. }
  165. time.Sleep(10 * time.Millisecond)
  166. }
  167. if updating {
  168. b.t.Fatalf("update did not finish")
  169. }
  170. sections = expectd / b.indexer.sectionSize
  171. break
  172. }
  173. select {
  174. case <-time.After(10 * time.Second):
  175. b.t.Fatalf("Expected processed block #%d, got nothing", expectd)
  176. case processed := <-b.processCh:
  177. if processed != expectd {
  178. b.t.Errorf("Expected processed block #%d, got #%d", expectd, processed)
  179. }
  180. }
  181. }
  182. b.stored = sections
  183. }
  184. }
  185. if b.stored == 0 {
  186. return 0, false
  187. }
  188. return b.stored*b.indexer.sectionSize - 1, true
  189. }
  190. func (b *testChainIndexBackend) reorg(headNum uint64) uint64 {
  191. firstChanged := (headNum + 1) / b.indexer.sectionSize
  192. if firstChanged < b.stored {
  193. b.stored = firstChanged
  194. }
  195. return b.stored * b.indexer.sectionSize
  196. }
  197. func (b *testChainIndexBackend) Reset(ctx context.Context, section uint64, prevHead common.Hash) error {
  198. b.section = section
  199. b.headerCnt = 0
  200. return nil
  201. }
  202. func (b *testChainIndexBackend) Process(ctx context.Context, header *types.Header) error {
  203. b.headerCnt++
  204. if b.headerCnt > b.indexer.sectionSize {
  205. b.t.Error("Processing too many headers")
  206. }
  207. //t.processCh <- header.Number.Uint64()
  208. select {
  209. case <-time.After(10 * time.Second):
  210. b.t.Error("Unexpected call to Process")
  211. // Can't use Fatal since this is not the test's goroutine.
  212. // Returning error stops the chainIndexer's updateLoop
  213. return errors.New("Unexpected call to Process")
  214. case b.processCh <- header.Number.Uint64():
  215. }
  216. return nil
  217. }
  218. func (b *testChainIndexBackend) Commit() error {
  219. if b.headerCnt != b.indexer.sectionSize {
  220. b.t.Error("Not enough headers processed")
  221. }
  222. return nil
  223. }
  224. func (b *testChainIndexBackend) Prune(threshold uint64) error {
  225. return nil
  226. }