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