github.com/phillinzzz/newBsc@v1.1.6/eth/filters/filter.go (about)

     1  // Copyright 2014 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 filters
    18  
    19  import (
    20  	"context"
    21  	"errors"
    22  	"fmt"
    23  	"math/big"
    24  
    25  	"github.com/phillinzzz/newBsc/common"
    26  	"github.com/phillinzzz/newBsc/core"
    27  	"github.com/phillinzzz/newBsc/core/bloombits"
    28  	"github.com/phillinzzz/newBsc/core/types"
    29  	"github.com/phillinzzz/newBsc/ethdb"
    30  	"github.com/phillinzzz/newBsc/event"
    31  	"github.com/phillinzzz/newBsc/rpc"
    32  )
    33  
    34  const maxFilterBlockRange = 5000
    35  
    36  type Backend interface {
    37  	ChainDb() ethdb.Database
    38  	HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error)
    39  	HeaderByHash(ctx context.Context, blockHash common.Hash) (*types.Header, error)
    40  	GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
    41  	GetLogs(ctx context.Context, blockHash common.Hash) ([][]*types.Log, error)
    42  
    43  	SubscribeNewTxsEvent(chan<- core.NewTxsEvent) event.Subscription
    44  	SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
    45  	SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
    46  	SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription
    47  	SubscribePendingLogsEvent(ch chan<- []*types.Log) event.Subscription
    48  
    49  	BloomStatus() (uint64, uint64)
    50  	ServiceFilter(ctx context.Context, session *bloombits.MatcherSession)
    51  }
    52  
    53  // Filter can be used to retrieve and filter logs.
    54  type Filter struct {
    55  	backend Backend
    56  
    57  	db        ethdb.Database
    58  	addresses []common.Address
    59  	topics    [][]common.Hash
    60  
    61  	block      common.Hash // Block hash if filtering a single block
    62  	begin, end int64       // Range interval if filtering multiple blocks
    63  
    64  	matcher *bloombits.Matcher
    65  
    66  	rangeLimit bool
    67  }
    68  
    69  // NewRangeFilter creates a new filter which uses a bloom filter on blocks to
    70  // figure out whether a particular block is interesting or not.
    71  func NewRangeFilter(backend Backend, begin, end int64, addresses []common.Address, topics [][]common.Hash, rangeLimit bool) *Filter {
    72  	// Flatten the address and topic filter clauses into a single bloombits filter
    73  	// system. Since the bloombits are not positional, nil topics are permitted,
    74  	// which get flattened into a nil byte slice.
    75  	var filters [][][]byte
    76  	if len(addresses) > 0 {
    77  		filter := make([][]byte, len(addresses))
    78  		for i, address := range addresses {
    79  			filter[i] = address.Bytes()
    80  		}
    81  		filters = append(filters, filter)
    82  	}
    83  	for _, topicList := range topics {
    84  		filter := make([][]byte, len(topicList))
    85  		for i, topic := range topicList {
    86  			filter[i] = topic.Bytes()
    87  		}
    88  		filters = append(filters, filter)
    89  	}
    90  	size, _ := backend.BloomStatus()
    91  
    92  	// Create a generic filter and convert it into a range filter
    93  	filter := newFilter(backend, addresses, topics)
    94  
    95  	filter.matcher = bloombits.NewMatcher(size, filters)
    96  	filter.begin = begin
    97  	filter.end = end
    98  	filter.rangeLimit = rangeLimit
    99  
   100  	return filter
   101  }
   102  
   103  // NewBlockFilter creates a new filter which directly inspects the contents of
   104  // a block to figure out whether it is interesting or not.
   105  func NewBlockFilter(backend Backend, block common.Hash, addresses []common.Address, topics [][]common.Hash) *Filter {
   106  	// Create a generic filter and convert it into a block filter
   107  	filter := newFilter(backend, addresses, topics)
   108  	filter.block = block
   109  	return filter
   110  }
   111  
   112  // newFilter creates a generic filter that can either filter based on a block hash,
   113  // or based on range queries. The search criteria needs to be explicitly set.
   114  func newFilter(backend Backend, addresses []common.Address, topics [][]common.Hash) *Filter {
   115  	return &Filter{
   116  		backend:   backend,
   117  		addresses: addresses,
   118  		topics:    topics,
   119  		db:        backend.ChainDb(),
   120  	}
   121  }
   122  
   123  // Logs searches the blockchain for matching log entries, returning all from the
   124  // first block that contains matches, updating the start of the filter accordingly.
   125  func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) {
   126  	// If we're doing singleton block filtering, execute and return
   127  	if f.block != (common.Hash{}) {
   128  		header, err := f.backend.HeaderByHash(ctx, f.block)
   129  		if err != nil {
   130  			return nil, err
   131  		}
   132  		if header == nil {
   133  			return nil, errors.New("unknown block")
   134  		}
   135  		return f.blockLogs(ctx, header)
   136  	}
   137  	// Figure out the limits of the filter range
   138  	header, _ := f.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
   139  	if header == nil {
   140  		return nil, nil
   141  	}
   142  	head := header.Number.Uint64()
   143  
   144  	if f.begin == -1 {
   145  		f.begin = int64(head)
   146  	}
   147  	end := uint64(f.end)
   148  	if f.end == -1 {
   149  		end = head
   150  	}
   151  	if f.rangeLimit && (int64(end)-f.begin) > maxFilterBlockRange {
   152  		return nil, fmt.Errorf("exceed maximum block range: %d", maxFilterBlockRange)
   153  	}
   154  	// Gather all indexed logs, and finish with non indexed ones
   155  	var (
   156  		logs []*types.Log
   157  		err  error
   158  	)
   159  	size, sections := f.backend.BloomStatus()
   160  	if indexed := sections * size; indexed > uint64(f.begin) {
   161  		if indexed > end {
   162  			logs, err = f.indexedLogs(ctx, end)
   163  		} else {
   164  			logs, err = f.indexedLogs(ctx, indexed-1)
   165  		}
   166  		if err != nil {
   167  			return logs, err
   168  		}
   169  	}
   170  	rest, err := f.unindexedLogs(ctx, end)
   171  	logs = append(logs, rest...)
   172  	return logs, err
   173  }
   174  
   175  // indexedLogs returns the logs matching the filter criteria based on the bloom
   176  // bits indexed available locally or via the network.
   177  func (f *Filter) indexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
   178  	// Create a matcher session and request servicing from the backend
   179  	matches := make(chan uint64, 64)
   180  
   181  	session, err := f.matcher.Start(ctx, uint64(f.begin), end, matches)
   182  	if err != nil {
   183  		return nil, err
   184  	}
   185  	defer session.Close()
   186  
   187  	f.backend.ServiceFilter(ctx, session)
   188  
   189  	// Iterate over the matches until exhausted or context closed
   190  	var logs []*types.Log
   191  
   192  	for {
   193  		select {
   194  		case number, ok := <-matches:
   195  			// Abort if all matches have been fulfilled
   196  			if !ok {
   197  				err := session.Error()
   198  				if err == nil {
   199  					f.begin = int64(end) + 1
   200  				}
   201  				return logs, err
   202  			}
   203  			f.begin = int64(number) + 1
   204  
   205  			// Retrieve the suggested block and pull any truly matching logs
   206  			header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(number))
   207  			if header == nil || err != nil {
   208  				return logs, err
   209  			}
   210  			found, err := f.checkMatches(ctx, header)
   211  			if err != nil {
   212  				return logs, err
   213  			}
   214  			logs = append(logs, found...)
   215  
   216  		case <-ctx.Done():
   217  			return logs, ctx.Err()
   218  		}
   219  	}
   220  }
   221  
   222  // unindexedLogs returns the logs matching the filter criteria based on raw block
   223  // iteration and bloom matching.
   224  func (f *Filter) unindexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
   225  	var logs []*types.Log
   226  
   227  	for ; f.begin <= int64(end); f.begin++ {
   228  		header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(f.begin))
   229  		if header == nil || err != nil {
   230  			return logs, err
   231  		}
   232  		found, err := f.blockLogs(ctx, header)
   233  		if err != nil {
   234  			return logs, err
   235  		}
   236  		logs = append(logs, found...)
   237  	}
   238  	return logs, nil
   239  }
   240  
   241  // blockLogs returns the logs matching the filter criteria within a single block.
   242  func (f *Filter) blockLogs(ctx context.Context, header *types.Header) (logs []*types.Log, err error) {
   243  	if bloomFilter(header.Bloom, f.addresses, f.topics) {
   244  		found, err := f.checkMatches(ctx, header)
   245  		if err != nil {
   246  			return logs, err
   247  		}
   248  		logs = append(logs, found...)
   249  	}
   250  	return logs, nil
   251  }
   252  
   253  // checkMatches checks if the receipts belonging to the given header contain any log events that
   254  // match the filter criteria. This function is called when the bloom filter signals a potential match.
   255  func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs []*types.Log, err error) {
   256  	// Get the logs of the block
   257  	logsList, err := f.backend.GetLogs(ctx, header.Hash())
   258  	if err != nil {
   259  		return nil, err
   260  	}
   261  	var unfiltered []*types.Log
   262  	for _, logs := range logsList {
   263  		unfiltered = append(unfiltered, logs...)
   264  	}
   265  	logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics)
   266  	if len(logs) > 0 {
   267  		// We have matching logs, check if we need to resolve full logs via the light client
   268  		if logs[0].TxHash == (common.Hash{}) {
   269  			receipts, err := f.backend.GetReceipts(ctx, header.Hash())
   270  			if err != nil {
   271  				return nil, err
   272  			}
   273  			unfiltered = unfiltered[:0]
   274  			for _, receipt := range receipts {
   275  				unfiltered = append(unfiltered, receipt.Logs...)
   276  			}
   277  			logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics)
   278  		}
   279  		return logs, nil
   280  	}
   281  	return nil, nil
   282  }
   283  
   284  func includes(addresses []common.Address, a common.Address) bool {
   285  	for _, addr := range addresses {
   286  		if addr == a {
   287  			return true
   288  		}
   289  	}
   290  
   291  	return false
   292  }
   293  
   294  // filterLogs creates a slice of logs matching the given criteria.
   295  func filterLogs(logs []*types.Log, fromBlock, toBlock *big.Int, addresses []common.Address, topics [][]common.Hash) []*types.Log {
   296  	var ret []*types.Log
   297  Logs:
   298  	for _, log := range logs {
   299  		if fromBlock != nil && fromBlock.Int64() >= 0 && fromBlock.Uint64() > log.BlockNumber {
   300  			continue
   301  		}
   302  		if toBlock != nil && toBlock.Int64() >= 0 && toBlock.Uint64() < log.BlockNumber {
   303  			continue
   304  		}
   305  
   306  		if len(addresses) > 0 && !includes(addresses, log.Address) {
   307  			continue
   308  		}
   309  		// If the to filtered topics is greater than the amount of topics in logs, skip.
   310  		if len(topics) > len(log.Topics) {
   311  			continue Logs
   312  		}
   313  		for i, sub := range topics {
   314  			match := len(sub) == 0 // empty rule set == wildcard
   315  			for _, topic := range sub {
   316  				if log.Topics[i] == topic {
   317  					match = true
   318  					break
   319  				}
   320  			}
   321  			if !match {
   322  				continue Logs
   323  			}
   324  		}
   325  		ret = append(ret, log)
   326  	}
   327  	return ret
   328  }
   329  
   330  func bloomFilter(bloom types.Bloom, addresses []common.Address, topics [][]common.Hash) bool {
   331  	if len(addresses) > 0 {
   332  		var included bool
   333  		for _, addr := range addresses {
   334  			if types.BloomLookup(bloom, addr) {
   335  				included = true
   336  				break
   337  			}
   338  		}
   339  		if !included {
   340  			return false
   341  		}
   342  	}
   343  
   344  	for _, sub := range topics {
   345  		included := len(sub) == 0 // empty rule set == wildcard
   346  		for _, topic := range sub {
   347  			if types.BloomLookup(bloom, topic) {
   348  				included = true
   349  				break
   350  			}
   351  		}
   352  		if !included {
   353  			return false
   354  		}
   355  	}
   356  	return true
   357  }