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