matcher_test.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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 bloombits
  17. import (
  18. "context"
  19. "math/rand"
  20. "sync/atomic"
  21. "testing"
  22. "time"
  23. "github.com/ethereum/go-ethereum/common"
  24. )
  25. const testSectionSize = 4096
  26. // Tests that wildcard filter rules (nil) can be specified and are handled well.
  27. func TestMatcherWildcards(t *testing.T) {
  28. matcher := NewMatcher(testSectionSize, [][][]byte{
  29. {common.Address{}.Bytes(), common.Address{0x01}.Bytes()}, // Default address is not a wildcard
  30. {common.Hash{}.Bytes(), common.Hash{0x01}.Bytes()}, // Default hash is not a wildcard
  31. {common.Hash{0x01}.Bytes()}, // Plain rule, sanity check
  32. {common.Hash{0x01}.Bytes(), nil}, // Wildcard suffix, drop rule
  33. {nil, common.Hash{0x01}.Bytes()}, // Wildcard prefix, drop rule
  34. {nil, nil}, // Wildcard combo, drop rule
  35. {}, // Inited wildcard rule, drop rule
  36. nil, // Proper wildcard rule, drop rule
  37. })
  38. if len(matcher.filters) != 3 {
  39. t.Fatalf("filter system size mismatch: have %d, want %d", len(matcher.filters), 3)
  40. }
  41. if len(matcher.filters[0]) != 2 {
  42. t.Fatalf("address clause size mismatch: have %d, want %d", len(matcher.filters[0]), 2)
  43. }
  44. if len(matcher.filters[1]) != 2 {
  45. t.Fatalf("combo topic clause size mismatch: have %d, want %d", len(matcher.filters[1]), 2)
  46. }
  47. if len(matcher.filters[2]) != 1 {
  48. t.Fatalf("singletone topic clause size mismatch: have %d, want %d", len(matcher.filters[2]), 1)
  49. }
  50. }
  51. // Tests the matcher pipeline on a single continuous workflow without interrupts.
  52. func TestMatcherContinuous(t *testing.T) {
  53. testMatcherDiffBatches(t, [][]bloomIndexes{{{10, 20, 30}}}, 100000, false, 75)
  54. testMatcherDiffBatches(t, [][]bloomIndexes{{{32, 3125, 100}}, {{40, 50, 10}}}, 100000, false, 81)
  55. testMatcherDiffBatches(t, [][]bloomIndexes{{{4, 8, 11}, {7, 8, 17}}, {{9, 9, 12}, {15, 20, 13}}, {{18, 15, 15}, {12, 10, 4}}}, 10000, false, 36)
  56. }
  57. // Tests the matcher pipeline on a constantly interrupted and resumed work pattern
  58. // with the aim of ensuring data items are requested only once.
  59. func TestMatcherIntermittent(t *testing.T) {
  60. testMatcherDiffBatches(t, [][]bloomIndexes{{{10, 20, 30}}}, 100000, true, 75)
  61. testMatcherDiffBatches(t, [][]bloomIndexes{{{32, 3125, 100}}, {{40, 50, 10}}}, 100000, true, 81)
  62. testMatcherDiffBatches(t, [][]bloomIndexes{{{4, 8, 11}, {7, 8, 17}}, {{9, 9, 12}, {15, 20, 13}}, {{18, 15, 15}, {12, 10, 4}}}, 10000, true, 36)
  63. }
  64. // Tests the matcher pipeline on random input to hopefully catch anomalies.
  65. func TestMatcherRandom(t *testing.T) {
  66. for i := 0; i < 10; i++ {
  67. testMatcherBothModes(t, makeRandomIndexes([]int{1}, 50), 10000, 0)
  68. testMatcherBothModes(t, makeRandomIndexes([]int{3}, 50), 10000, 0)
  69. testMatcherBothModes(t, makeRandomIndexes([]int{2, 2, 2}, 20), 10000, 0)
  70. testMatcherBothModes(t, makeRandomIndexes([]int{5, 5, 5}, 50), 10000, 0)
  71. testMatcherBothModes(t, makeRandomIndexes([]int{4, 4, 4}, 20), 10000, 0)
  72. }
  73. }
  74. // Tests that matching on everything doesn't crash (special case internally).
  75. func TestWildcardMatcher(t *testing.T) {
  76. testMatcherBothModes(t, nil, 10000, 0)
  77. }
  78. // makeRandomIndexes generates a random filter system, composed on multiple filter
  79. // criteria, each having one bloom list component for the address and arbitrarily
  80. // many topic bloom list components.
  81. func makeRandomIndexes(lengths []int, max int) [][]bloomIndexes {
  82. res := make([][]bloomIndexes, len(lengths))
  83. for i, topics := range lengths {
  84. res[i] = make([]bloomIndexes, topics)
  85. for j := 0; j < topics; j++ {
  86. for k := 0; k < len(res[i][j]); k++ {
  87. res[i][j][k] = uint(rand.Intn(max-1) + 2)
  88. }
  89. }
  90. }
  91. return res
  92. }
  93. // testMatcherDiffBatches runs the given matches test in single-delivery and also
  94. // in batches delivery mode, verifying that all kinds of deliveries are handled
  95. // correctly withn.
  96. func testMatcherDiffBatches(t *testing.T, filter [][]bloomIndexes, blocks uint64, intermittent bool, retrievals uint32) {
  97. singleton := testMatcher(t, filter, blocks, intermittent, retrievals, 1)
  98. batched := testMatcher(t, filter, blocks, intermittent, retrievals, 16)
  99. if singleton != batched {
  100. t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, %v in signleton vs. %v in batched mode", filter, blocks, intermittent, singleton, batched)
  101. }
  102. }
  103. // testMatcherBothModes runs the given matcher test in both continuous as well as
  104. // in intermittent mode, verifying that the request counts match each other.
  105. func testMatcherBothModes(t *testing.T, filter [][]bloomIndexes, blocks uint64, retrievals uint32) {
  106. continuous := testMatcher(t, filter, blocks, false, retrievals, 16)
  107. intermittent := testMatcher(t, filter, blocks, true, retrievals, 16)
  108. if continuous != intermittent {
  109. t.Errorf("filter = %v blocks = %v: request count mismatch, %v in continuous vs. %v in intermittent mode", filter, blocks, continuous, intermittent)
  110. }
  111. }
  112. // testMatcher is a generic tester to run the given matcher test and return the
  113. // number of requests made for cross validation between different modes.
  114. func testMatcher(t *testing.T, filter [][]bloomIndexes, blocks uint64, intermittent bool, retrievals uint32, maxReqCount int) uint32 {
  115. // Create a new matcher an simulate our explicit random bitsets
  116. matcher := NewMatcher(testSectionSize, nil)
  117. matcher.filters = filter
  118. for _, rule := range filter {
  119. for _, topic := range rule {
  120. for _, bit := range topic {
  121. matcher.addScheduler(bit)
  122. }
  123. }
  124. }
  125. // Track the number of retrieval requests made
  126. var requested uint32
  127. // Start the matching session for the filter and the retriver goroutines
  128. quit := make(chan struct{})
  129. matches := make(chan uint64, 16)
  130. session, err := matcher.Start(context.Background(), 0, blocks-1, matches)
  131. if err != nil {
  132. t.Fatalf("failed to stat matcher session: %v", err)
  133. }
  134. startRetrievers(session, quit, &requested, maxReqCount)
  135. // Iterate over all the blocks and verify that the pipeline produces the correct matches
  136. for i := uint64(0); i < blocks; i++ {
  137. if expMatch3(filter, i) {
  138. match, ok := <-matches
  139. if !ok {
  140. t.Errorf("filter = %v blocks = %v intermittent = %v: expected #%v, results channel closed", filter, blocks, intermittent, i)
  141. return 0
  142. }
  143. if match != i {
  144. t.Errorf("filter = %v blocks = %v intermittent = %v: expected #%v, got #%v", filter, blocks, intermittent, i, match)
  145. }
  146. // If we're testing intermittent mode, abort and restart the pipeline
  147. if intermittent {
  148. session.Close()
  149. close(quit)
  150. quit = make(chan struct{})
  151. matches = make(chan uint64, 16)
  152. session, err = matcher.Start(context.Background(), i+1, blocks-1, matches)
  153. if err != nil {
  154. t.Fatalf("failed to stat matcher session: %v", err)
  155. }
  156. startRetrievers(session, quit, &requested, maxReqCount)
  157. }
  158. }
  159. }
  160. // Ensure the result channel is torn down after the last block
  161. match, ok := <-matches
  162. if ok {
  163. t.Errorf("filter = %v blocks = %v intermittent = %v: expected closed channel, got #%v", filter, blocks, intermittent, match)
  164. }
  165. // Clean up the session and ensure we match the expected retrieval count
  166. session.Close()
  167. close(quit)
  168. if retrievals != 0 && requested != retrievals {
  169. t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, have #%v, want #%v", filter, blocks, intermittent, requested, retrievals)
  170. }
  171. return requested
  172. }
  173. // startRetrievers starts a batch of goroutines listening for section requests
  174. // and serving them.
  175. func startRetrievers(session *MatcherSession, quit chan struct{}, retrievals *uint32, batch int) {
  176. requests := make(chan chan *Retrieval)
  177. for i := 0; i < 10; i++ {
  178. // Start a multiplexer to test multiple threaded execution
  179. go session.Multiplex(batch, 100*time.Microsecond, requests)
  180. // Start a services to match the above multiplexer
  181. go func() {
  182. for {
  183. // Wait for a service request or a shutdown
  184. select {
  185. case <-quit:
  186. return
  187. case request := <-requests:
  188. task := <-request
  189. task.Bitsets = make([][]byte, len(task.Sections))
  190. for i, section := range task.Sections {
  191. if rand.Int()%4 != 0 { // Handle occasional missing deliveries
  192. task.Bitsets[i] = generateBitset(task.Bit, section)
  193. atomic.AddUint32(retrievals, 1)
  194. }
  195. }
  196. request <- task
  197. }
  198. }
  199. }()
  200. }
  201. }
  202. // generateBitset generates the rotated bitset for the given bloom bit and section
  203. // numbers.
  204. func generateBitset(bit uint, section uint64) []byte {
  205. bitset := make([]byte, testSectionSize/8)
  206. for i := 0; i < len(bitset); i++ {
  207. for b := 0; b < 8; b++ {
  208. blockIdx := section*testSectionSize + uint64(i*8+b)
  209. bitset[i] += bitset[i]
  210. if (blockIdx % uint64(bit)) == 0 {
  211. bitset[i]++
  212. }
  213. }
  214. }
  215. return bitset
  216. }
  217. func expMatch1(filter bloomIndexes, i uint64) bool {
  218. for _, ii := range filter {
  219. if (i % uint64(ii)) != 0 {
  220. return false
  221. }
  222. }
  223. return true
  224. }
  225. func expMatch2(filter []bloomIndexes, i uint64) bool {
  226. for _, ii := range filter {
  227. if expMatch1(ii, i) {
  228. return true
  229. }
  230. }
  231. return false
  232. }
  233. func expMatch3(filter [][]bloomIndexes, i uint64) bool {
  234. for _, ii := range filter {
  235. if !expMatch2(ii, i) {
  236. return false
  237. }
  238. }
  239. return true
  240. }