matcher_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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}}}, 0, 100000, false, 75)
  54. testMatcherDiffBatches(t, [][]bloomIndexes{{{32, 3125, 100}}, {{40, 50, 10}}}, 0, 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}}}, 0, 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}}}, 0, 100000, true, 75)
  61. testMatcherDiffBatches(t, [][]bloomIndexes{{{32, 3125, 100}}, {{40, 50, 10}}}, 0, 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}}}, 0, 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), 0, 10000, 0)
  68. testMatcherBothModes(t, makeRandomIndexes([]int{3}, 50), 0, 10000, 0)
  69. testMatcherBothModes(t, makeRandomIndexes([]int{2, 2, 2}, 20), 0, 10000, 0)
  70. testMatcherBothModes(t, makeRandomIndexes([]int{5, 5, 5}, 50), 0, 10000, 0)
  71. testMatcherBothModes(t, makeRandomIndexes([]int{4, 4, 4}, 20), 0, 10000, 0)
  72. }
  73. }
  74. // Tests that the matcher can properly find matches if the starting block is
  75. // shifter from a multiple of 8. This is needed to cover an optimisation with
  76. // bitset matching https://github.com/ethereum/go-ethereum/issues/15309.
  77. func TestMatcherShifted(t *testing.T) {
  78. // Block 0 always matches in the tests, skip ahead of first 8 blocks with the
  79. // start to get a potential zero byte in the matcher bitset.
  80. // To keep the second bitset byte zero, the filter must only match for the first
  81. // time in block 16, so doing an all-16 bit filter should suffice.
  82. // To keep the starting block non divisible by 8, block number 9 is the first
  83. // that would introduce a shift and not match block 0.
  84. testMatcherBothModes(t, [][]bloomIndexes{{{16, 16, 16}}}, 9, 64, 0)
  85. }
  86. // Tests that matching on everything doesn't crash (special case internally).
  87. func TestWildcardMatcher(t *testing.T) {
  88. testMatcherBothModes(t, nil, 0, 10000, 0)
  89. }
  90. // makeRandomIndexes generates a random filter system, composed on multiple filter
  91. // criteria, each having one bloom list component for the address and arbitrarily
  92. // many topic bloom list components.
  93. func makeRandomIndexes(lengths []int, max int) [][]bloomIndexes {
  94. res := make([][]bloomIndexes, len(lengths))
  95. for i, topics := range lengths {
  96. res[i] = make([]bloomIndexes, topics)
  97. for j := 0; j < topics; j++ {
  98. for k := 0; k < len(res[i][j]); k++ {
  99. res[i][j][k] = uint(rand.Intn(max-1) + 2)
  100. }
  101. }
  102. }
  103. return res
  104. }
  105. // testMatcherDiffBatches runs the given matches test in single-delivery and also
  106. // in batches delivery mode, verifying that all kinds of deliveries are handled
  107. // correctly withn.
  108. func testMatcherDiffBatches(t *testing.T, filter [][]bloomIndexes, start, blocks uint64, intermittent bool, retrievals uint32) {
  109. singleton := testMatcher(t, filter, start, blocks, intermittent, retrievals, 1)
  110. batched := testMatcher(t, filter, start, blocks, intermittent, retrievals, 16)
  111. if singleton != batched {
  112. t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, %v in signleton vs. %v in batched mode", filter, blocks, intermittent, singleton, batched)
  113. }
  114. }
  115. // testMatcherBothModes runs the given matcher test in both continuous as well as
  116. // in intermittent mode, verifying that the request counts match each other.
  117. func testMatcherBothModes(t *testing.T, filter [][]bloomIndexes, start, blocks uint64, retrievals uint32) {
  118. continuous := testMatcher(t, filter, start, blocks, false, retrievals, 16)
  119. intermittent := testMatcher(t, filter, start, blocks, true, retrievals, 16)
  120. if continuous != intermittent {
  121. t.Errorf("filter = %v blocks = %v: request count mismatch, %v in continuous vs. %v in intermittent mode", filter, blocks, continuous, intermittent)
  122. }
  123. }
  124. // testMatcher is a generic tester to run the given matcher test and return the
  125. // number of requests made for cross validation between different modes.
  126. func testMatcher(t *testing.T, filter [][]bloomIndexes, start, blocks uint64, intermittent bool, retrievals uint32, maxReqCount int) uint32 {
  127. // Create a new matcher an simulate our explicit random bitsets
  128. matcher := NewMatcher(testSectionSize, nil)
  129. matcher.filters = filter
  130. for _, rule := range filter {
  131. for _, topic := range rule {
  132. for _, bit := range topic {
  133. matcher.addScheduler(bit)
  134. }
  135. }
  136. }
  137. // Track the number of retrieval requests made
  138. var requested uint32
  139. // Start the matching session for the filter and the retriver goroutines
  140. quit := make(chan struct{})
  141. matches := make(chan uint64, 16)
  142. session, err := matcher.Start(context.Background(), start, blocks-1, matches)
  143. if err != nil {
  144. t.Fatalf("failed to stat matcher session: %v", err)
  145. }
  146. startRetrievers(session, quit, &requested, maxReqCount)
  147. // Iterate over all the blocks and verify that the pipeline produces the correct matches
  148. for i := start; i < blocks; i++ {
  149. if expMatch3(filter, i) {
  150. match, ok := <-matches
  151. if !ok {
  152. t.Errorf("filter = %v blocks = %v intermittent = %v: expected #%v, results channel closed", filter, blocks, intermittent, i)
  153. return 0
  154. }
  155. if match != i {
  156. t.Errorf("filter = %v blocks = %v intermittent = %v: expected #%v, got #%v", filter, blocks, intermittent, i, match)
  157. }
  158. // If we're testing intermittent mode, abort and restart the pipeline
  159. if intermittent {
  160. session.Close()
  161. close(quit)
  162. quit = make(chan struct{})
  163. matches = make(chan uint64, 16)
  164. session, err = matcher.Start(context.Background(), i+1, blocks-1, matches)
  165. if err != nil {
  166. t.Fatalf("failed to stat matcher session: %v", err)
  167. }
  168. startRetrievers(session, quit, &requested, maxReqCount)
  169. }
  170. }
  171. }
  172. // Ensure the result channel is torn down after the last block
  173. match, ok := <-matches
  174. if ok {
  175. t.Errorf("filter = %v blocks = %v intermittent = %v: expected closed channel, got #%v", filter, blocks, intermittent, match)
  176. }
  177. // Clean up the session and ensure we match the expected retrieval count
  178. session.Close()
  179. close(quit)
  180. if retrievals != 0 && requested != retrievals {
  181. t.Errorf("filter = %v blocks = %v intermittent = %v: request count mismatch, have #%v, want #%v", filter, blocks, intermittent, requested, retrievals)
  182. }
  183. return requested
  184. }
  185. // startRetrievers starts a batch of goroutines listening for section requests
  186. // and serving them.
  187. func startRetrievers(session *MatcherSession, quit chan struct{}, retrievals *uint32, batch int) {
  188. requests := make(chan chan *Retrieval)
  189. for i := 0; i < 10; i++ {
  190. // Start a multiplexer to test multiple threaded execution
  191. go session.Multiplex(batch, 100*time.Microsecond, requests)
  192. // Start a services to match the above multiplexer
  193. go func() {
  194. for {
  195. // Wait for a service request or a shutdown
  196. select {
  197. case <-quit:
  198. return
  199. case request := <-requests:
  200. task := <-request
  201. task.Bitsets = make([][]byte, len(task.Sections))
  202. for i, section := range task.Sections {
  203. if rand.Int()%4 != 0 { // Handle occasional missing deliveries
  204. task.Bitsets[i] = generateBitset(task.Bit, section)
  205. atomic.AddUint32(retrievals, 1)
  206. }
  207. }
  208. request <- task
  209. }
  210. }
  211. }()
  212. }
  213. }
  214. // generateBitset generates the rotated bitset for the given bloom bit and section
  215. // numbers.
  216. func generateBitset(bit uint, section uint64) []byte {
  217. bitset := make([]byte, testSectionSize/8)
  218. for i := 0; i < len(bitset); i++ {
  219. for b := 0; b < 8; b++ {
  220. blockIdx := section*testSectionSize + uint64(i*8+b)
  221. bitset[i] += bitset[i]
  222. if (blockIdx % uint64(bit)) == 0 {
  223. bitset[i]++
  224. }
  225. }
  226. }
  227. return bitset
  228. }
  229. func expMatch1(filter bloomIndexes, i uint64) bool {
  230. for _, ii := range filter {
  231. if (i % uint64(ii)) != 0 {
  232. return false
  233. }
  234. }
  235. return true
  236. }
  237. func expMatch2(filter []bloomIndexes, i uint64) bool {
  238. for _, ii := range filter {
  239. if expMatch1(ii, i) {
  240. return true
  241. }
  242. }
  243. return false
  244. }
  245. func expMatch3(filter [][]bloomIndexes, i uint64) bool {
  246. for _, ii := range filter {
  247. if !expMatch2(ii, i) {
  248. return false
  249. }
  250. }
  251. return true
  252. }