github.com/jimmyx0x/go-ethereum@v1.10.28/core/bloombits/matcher_test.go (about)

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