github.com/pfcoder/quorum@v2.0.3-0.20180501191142-d4a1b0958135+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  	"math/big"
    22  	"time"
    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/types"
    28  	"github.com/ethereum/go-ethereum/ethdb"
    29  	"github.com/ethereum/go-ethereum/event"
    30  	"github.com/ethereum/go-ethereum/rpc"
    31  )
    32  
    33  type Backend interface {
    34  	ChainDb() ethdb.Database
    35  	EventMux() *event.TypeMux
    36  	HeaderByNumber(ctx context.Context, blockNr rpc.BlockNumber) (*types.Header, error)
    37  	GetReceipts(ctx context.Context, blockHash common.Hash) (types.Receipts, error)
    38  
    39  	SubscribeTxPreEvent(chan<- core.TxPreEvent) event.Subscription
    40  	SubscribeChainEvent(ch chan<- core.ChainEvent) event.Subscription
    41  	SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription
    42  	SubscribeLogsEvent(ch chan<- []*types.Log) event.Subscription
    43  
    44  	BloomStatus() (uint64, uint64)
    45  	ServiceFilter(ctx context.Context, session *bloombits.MatcherSession)
    46  }
    47  
    48  // Filter can be used to retrieve and filter logs.
    49  type Filter struct {
    50  	backend Backend
    51  
    52  	db         ethdb.Database
    53  	begin, end int64
    54  	addresses  []common.Address
    55  	topics     [][]common.Hash
    56  
    57  	matcher *bloombits.Matcher
    58  }
    59  
    60  // New creates a new filter which uses a bloom filter on blocks to figure out whether
    61  // a particular block is interesting or not.
    62  func New(backend Backend, begin, end int64, addresses []common.Address, topics [][]common.Hash) *Filter {
    63  	// Flatten the address and topic filter clauses into a single bloombits filter
    64  	// system. Since the bloombits are not positional, nil topics are permitted,
    65  	// which get flattened into a nil byte slice.
    66  	var filters [][][]byte
    67  	if len(addresses) > 0 {
    68  		filter := make([][]byte, len(addresses))
    69  		for i, address := range addresses {
    70  			filter[i] = address.Bytes()
    71  		}
    72  		filters = append(filters, filter)
    73  	}
    74  	for _, topicList := range topics {
    75  		filter := make([][]byte, len(topicList))
    76  		for i, topic := range topicList {
    77  			filter[i] = topic.Bytes()
    78  		}
    79  		filters = append(filters, filter)
    80  	}
    81  	// Assemble and return the filter
    82  	size, _ := backend.BloomStatus()
    83  
    84  	return &Filter{
    85  		backend:   backend,
    86  		begin:     begin,
    87  		end:       end,
    88  		addresses: addresses,
    89  		topics:    topics,
    90  		db:        backend.ChainDb(),
    91  		matcher:   bloombits.NewMatcher(size, filters),
    92  	}
    93  }
    94  
    95  // Logs searches the blockchain for matching log entries, returning all from the
    96  // first block that contains matches, updating the start of the filter accordingly.
    97  func (f *Filter) Logs(ctx context.Context) ([]*types.Log, error) {
    98  	// Figure out the limits of the filter range
    99  	header, _ := f.backend.HeaderByNumber(ctx, rpc.LatestBlockNumber)
   100  	if header == nil {
   101  		return nil, nil
   102  	}
   103  	head := header.Number.Uint64()
   104  
   105  	if f.begin == -1 {
   106  		f.begin = int64(head)
   107  	}
   108  	end := uint64(f.end)
   109  	if f.end == -1 {
   110  		end = head
   111  	}
   112  	// Gather all indexed logs, and finish with non indexed ones
   113  	var (
   114  		logs []*types.Log
   115  		err  error
   116  	)
   117  	size, sections := f.backend.BloomStatus()
   118  	if indexed := sections * size; indexed > uint64(f.begin) {
   119  		if indexed > end {
   120  			logs, err = f.indexedLogs(ctx, end)
   121  		} else {
   122  			logs, err = f.indexedLogs(ctx, indexed-1)
   123  		}
   124  		if err != nil {
   125  			return logs, err
   126  		}
   127  	}
   128  	rest, err := f.unindexedLogs(ctx, end)
   129  	logs = append(logs, rest...)
   130  	return logs, err
   131  }
   132  
   133  // indexedLogs returns the logs matching the filter criteria based on the bloom
   134  // bits indexed available locally or via the network.
   135  func (f *Filter) indexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
   136  	// Create a matcher session and request servicing from the backend
   137  	matches := make(chan uint64, 64)
   138  
   139  	session, err := f.matcher.Start(uint64(f.begin), end, matches)
   140  	if err != nil {
   141  		return nil, err
   142  	}
   143  	defer session.Close(time.Second)
   144  
   145  	f.backend.ServiceFilter(ctx, session)
   146  
   147  	// Iterate over the matches until exhausted or context closed
   148  	var logs []*types.Log
   149  
   150  	for {
   151  		select {
   152  		case number, ok := <-matches:
   153  			// Abort if all matches have been fulfilled
   154  			if !ok {
   155  				f.begin = int64(end) + 1
   156  				return logs, nil
   157  			}
   158  			// Retrieve the suggested block and pull any truly matching logs
   159  			header, err := f.backend.HeaderByNumber(ctx, rpc.BlockNumber(number))
   160  			if header == nil || err != nil {
   161  				return logs, err
   162  			}
   163  			found, err := f.checkMatches(ctx, header)
   164  			if err != nil {
   165  				return logs, err
   166  			}
   167  			logs = append(logs, found...)
   168  
   169  		case <-ctx.Done():
   170  			return logs, ctx.Err()
   171  		}
   172  	}
   173  }
   174  
   175  // indexedLogs returns the logs matching the filter criteria based on raw block
   176  // iteration and bloom matching.
   177  func (f *Filter) unindexedLogs(ctx context.Context, end uint64) ([]*types.Log, error) {
   178  	var logs []*types.Log
   179  
   180  	for ; f.begin <= int64(end); f.begin++ {
   181  		blockNumber := rpc.BlockNumber(f.begin)
   182  		header, err := f.backend.HeaderByNumber(ctx, blockNumber)
   183  		if header == nil || err != nil {
   184  			return logs, err
   185  		}
   186  
   187  		bloomMatches := bloomFilter(header.Bloom, f.addresses, f.topics) ||
   188  			bloomFilter(core.GetPrivateBlockBloom(f.db, uint64(blockNumber)), f.addresses, f.topics)
   189  		if bloomMatches {
   190  			found, err := f.checkMatches(ctx, header)
   191  			if err != nil {
   192  				return logs, err
   193  			}
   194  			logs = append(logs, found...)
   195  		}
   196  	}
   197  	return logs, nil
   198  }
   199  
   200  // checkMatches checks if the receipts belonging to the given header contain any log events that
   201  // match the filter criteria. This function is called when the bloom filter signals a potential match.
   202  func (f *Filter) checkMatches(ctx context.Context, header *types.Header) (logs []*types.Log, err error) {
   203  	// Get the logs of the block
   204  	receipts, err := f.backend.GetReceipts(ctx, header.Hash())
   205  	if err != nil {
   206  		return nil, err
   207  	}
   208  	var unfiltered []*types.Log
   209  	for _, receipt := range receipts {
   210  		unfiltered = append(unfiltered, ([]*types.Log)(receipt.Logs)...)
   211  	}
   212  	logs = filterLogs(unfiltered, nil, nil, f.addresses, f.topics)
   213  	if len(logs) > 0 {
   214  		return logs, nil
   215  	}
   216  	return nil, nil
   217  }
   218  
   219  func includes(addresses []common.Address, a common.Address) bool {
   220  	for _, addr := range addresses {
   221  		if addr == a {
   222  			return true
   223  		}
   224  	}
   225  
   226  	return false
   227  }
   228  
   229  // filterLogs creates a slice of logs matching the given criteria.
   230  func filterLogs(logs []*types.Log, fromBlock, toBlock *big.Int, addresses []common.Address, topics [][]common.Hash) []*types.Log {
   231  	var ret []*types.Log
   232  Logs:
   233  	for _, log := range logs {
   234  		if fromBlock != nil && fromBlock.Int64() >= 0 && fromBlock.Uint64() > log.BlockNumber {
   235  			continue
   236  		}
   237  		if toBlock != nil && toBlock.Int64() >= 0 && toBlock.Uint64() < log.BlockNumber {
   238  			continue
   239  		}
   240  
   241  		if len(addresses) > 0 && !includes(addresses, log.Address) {
   242  			continue
   243  		}
   244  		// If the to filtered topics is greater than the amount of topics in logs, skip.
   245  		if len(topics) > len(log.Topics) {
   246  			continue Logs
   247  		}
   248  		for i, topics := range topics {
   249  			match := len(topics) == 0 // empty rule set == wildcard
   250  			for _, topic := range topics {
   251  				if log.Topics[i] == topic {
   252  					match = true
   253  					break
   254  				}
   255  			}
   256  			if !match {
   257  				continue Logs
   258  			}
   259  		}
   260  		ret = append(ret, log)
   261  	}
   262  	return ret
   263  }
   264  
   265  func bloomFilter(bloom types.Bloom, addresses []common.Address, topics [][]common.Hash) bool {
   266  	if len(addresses) > 0 {
   267  		var included bool
   268  		for _, addr := range addresses {
   269  			if types.BloomLookup(bloom, addr) {
   270  				included = true
   271  				break
   272  			}
   273  		}
   274  		if !included {
   275  			return false
   276  		}
   277  	}
   278  
   279  	for _, sub := range topics {
   280  		included := len(sub) == 0 // empty rule set == wildcard
   281  		for _, topic := range sub {
   282  			if types.BloomLookup(bloom, topic) {
   283  				included = true
   284  				break
   285  			}
   286  		}
   287  		if !included {
   288  			return false
   289  		}
   290  	}
   291  	return true
   292  }