chain_indexer_test.go 7.1 KB

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