github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/eth/filters/api.go (about)

     1  //  Copyright 2018 The go-ethereum Authors
     2  //  Copyright 2019 The go-aigar Authors
     3  //  This file is part of the go-aigar library.
     4  //
     5  //  The go-aigar library is free software: you can redistribute it and/or modify
     6  //  it under the terms of the GNU Lesser General Public License as published by
     7  //  the Free Software Foundation, either version 3 of the License, or
     8  //  (at your option) any later version.
     9  //
    10  //  The go-aigar library is distributed in the hope that it will be useful,
    11  //  but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  //  GNU Lesser General Public License for more details.
    14  //
    15  //  You should have received a copy of the GNU Lesser General Public License
    16  //  along with the go-aigar library. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  package filters
    19  
    20  import (
    21  	"context"
    22  	"encoding/json"
    23  	"errors"
    24  	"fmt"
    25  	"math/big"
    26  	"sync"
    27  	"time"
    28  
    29  	ethereum "github.com/AigarNetwork/aigar"
    30  	"github.com/AigarNetwork/aigar/common"
    31  	"github.com/AigarNetwork/aigar/common/hexutil"
    32  	"github.com/AigarNetwork/aigar/core/types"
    33  	"github.com/AigarNetwork/aigar/ethdb"
    34  	"github.com/AigarNetwork/aigar/event"
    35  	"github.com/AigarNetwork/aigar/rpc"
    36  )
    37  
    38  var (
    39  	deadline = 5 * time.Minute // consider a filter inactive if it has not been polled for within deadline
    40  )
    41  
    42  // filter is a helper struct that holds meta information over the filter type
    43  // and associated subscription in the event system.
    44  type filter struct {
    45  	typ      Type
    46  	deadline *time.Timer // filter is inactiv when deadline triggers
    47  	hashes   []common.Hash
    48  	crit     FilterCriteria
    49  	logs     []*types.Log
    50  	s        *Subscription // associated subscription in event system
    51  }
    52  
    53  // PublicFilterAPI offers support to create and manage filters. This will allow external clients to retrieve various
    54  // information related to the Ethereum protocol such als blocks, transactions and logs.
    55  type PublicFilterAPI struct {
    56  	backend   Backend
    57  	mux       *event.TypeMux
    58  	quit      chan struct{}
    59  	chainDb   ethdb.Database
    60  	events    *EventSystem
    61  	filtersMu sync.Mutex
    62  	filters   map[rpc.ID]*filter
    63  }
    64  
    65  // NewPublicFilterAPI returns a new PublicFilterAPI instance.
    66  func NewPublicFilterAPI(backend Backend, lightMode bool) *PublicFilterAPI {
    67  	api := &PublicFilterAPI{
    68  		backend: backend,
    69  		mux:     backend.EventMux(),
    70  		chainDb: backend.ChainDb(),
    71  		events:  NewEventSystem(backend.EventMux(), backend, lightMode),
    72  		filters: make(map[rpc.ID]*filter),
    73  	}
    74  	go api.timeoutLoop()
    75  
    76  	return api
    77  }
    78  
    79  // timeoutLoop runs every 5 minutes and deletes filters that have not been recently used.
    80  // Tt is started when the api is created.
    81  func (api *PublicFilterAPI) timeoutLoop() {
    82  	ticker := time.NewTicker(5 * time.Minute)
    83  	for {
    84  		<-ticker.C
    85  		api.filtersMu.Lock()
    86  		for id, f := range api.filters {
    87  			select {
    88  			case <-f.deadline.C:
    89  				f.s.Unsubscribe()
    90  				delete(api.filters, id)
    91  			default:
    92  				continue
    93  			}
    94  		}
    95  		api.filtersMu.Unlock()
    96  	}
    97  }
    98  
    99  // NewPendingTransactionFilter creates a filter that fetches pending transaction hashes
   100  // as transactions enter the pending state.
   101  //
   102  // It is part of the filter package because this filter can be used through the
   103  // `eth_getFilterChanges` polling method that is also used for log filters.
   104  //
   105  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newpendingtransactionfilter
   106  func (api *PublicFilterAPI) NewPendingTransactionFilter() rpc.ID {
   107  	var (
   108  		pendingTxs   = make(chan []common.Hash)
   109  		pendingTxSub = api.events.SubscribePendingTxs(pendingTxs)
   110  	)
   111  
   112  	api.filtersMu.Lock()
   113  	api.filters[pendingTxSub.ID] = &filter{typ: PendingTransactionsSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: pendingTxSub}
   114  	api.filtersMu.Unlock()
   115  
   116  	go func() {
   117  		for {
   118  			select {
   119  			case ph := <-pendingTxs:
   120  				api.filtersMu.Lock()
   121  				if f, found := api.filters[pendingTxSub.ID]; found {
   122  					f.hashes = append(f.hashes, ph...)
   123  				}
   124  				api.filtersMu.Unlock()
   125  			case <-pendingTxSub.Err():
   126  				api.filtersMu.Lock()
   127  				delete(api.filters, pendingTxSub.ID)
   128  				api.filtersMu.Unlock()
   129  				return
   130  			}
   131  		}
   132  	}()
   133  
   134  	return pendingTxSub.ID
   135  }
   136  
   137  // NewPendingTransactions creates a subscription that is triggered each time a transaction
   138  // enters the transaction pool and was signed from one of the transactions this nodes manages.
   139  func (api *PublicFilterAPI) NewPendingTransactions(ctx context.Context) (*rpc.Subscription, error) {
   140  	notifier, supported := rpc.NotifierFromContext(ctx)
   141  	if !supported {
   142  		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
   143  	}
   144  
   145  	rpcSub := notifier.CreateSubscription()
   146  
   147  	go func() {
   148  		txHashes := make(chan []common.Hash, 128)
   149  		pendingTxSub := api.events.SubscribePendingTxs(txHashes)
   150  
   151  		for {
   152  			select {
   153  			case hashes := <-txHashes:
   154  				// To keep the original behaviour, send a single tx hash in one notification.
   155  				// TODO(rjl493456442) Send a batch of tx hashes in one notification
   156  				for _, h := range hashes {
   157  					notifier.Notify(rpcSub.ID, h)
   158  				}
   159  			case <-rpcSub.Err():
   160  				pendingTxSub.Unsubscribe()
   161  				return
   162  			case <-notifier.Closed():
   163  				pendingTxSub.Unsubscribe()
   164  				return
   165  			}
   166  		}
   167  	}()
   168  
   169  	return rpcSub, nil
   170  }
   171  
   172  // NewBlockFilter creates a filter that fetches blocks that are imported into the chain.
   173  // It is part of the filter package since polling goes with eth_getFilterChanges.
   174  //
   175  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newblockfilter
   176  func (api *PublicFilterAPI) NewBlockFilter() rpc.ID {
   177  	var (
   178  		headers   = make(chan *types.Header)
   179  		headerSub = api.events.SubscribeNewHeads(headers)
   180  	)
   181  
   182  	api.filtersMu.Lock()
   183  	api.filters[headerSub.ID] = &filter{typ: BlocksSubscription, deadline: time.NewTimer(deadline), hashes: make([]common.Hash, 0), s: headerSub}
   184  	api.filtersMu.Unlock()
   185  
   186  	go func() {
   187  		for {
   188  			select {
   189  			case h := <-headers:
   190  				api.filtersMu.Lock()
   191  				if f, found := api.filters[headerSub.ID]; found {
   192  					f.hashes = append(f.hashes, h.Hash())
   193  				}
   194  				api.filtersMu.Unlock()
   195  			case <-headerSub.Err():
   196  				api.filtersMu.Lock()
   197  				delete(api.filters, headerSub.ID)
   198  				api.filtersMu.Unlock()
   199  				return
   200  			}
   201  		}
   202  	}()
   203  
   204  	return headerSub.ID
   205  }
   206  
   207  // NewHeads send a notification each time a new (header) block is appended to the chain.
   208  func (api *PublicFilterAPI) NewHeads(ctx context.Context) (*rpc.Subscription, error) {
   209  	notifier, supported := rpc.NotifierFromContext(ctx)
   210  	if !supported {
   211  		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
   212  	}
   213  
   214  	rpcSub := notifier.CreateSubscription()
   215  
   216  	go func() {
   217  		headers := make(chan *types.Header)
   218  		headersSub := api.events.SubscribeNewHeads(headers)
   219  
   220  		for {
   221  			select {
   222  			case h := <-headers:
   223  				notifier.Notify(rpcSub.ID, h)
   224  			case <-rpcSub.Err():
   225  				headersSub.Unsubscribe()
   226  				return
   227  			case <-notifier.Closed():
   228  				headersSub.Unsubscribe()
   229  				return
   230  			}
   231  		}
   232  	}()
   233  
   234  	return rpcSub, nil
   235  }
   236  
   237  // Logs creates a subscription that fires for all new log that match the given filter criteria.
   238  func (api *PublicFilterAPI) Logs(ctx context.Context, crit FilterCriteria) (*rpc.Subscription, error) {
   239  	notifier, supported := rpc.NotifierFromContext(ctx)
   240  	if !supported {
   241  		return &rpc.Subscription{}, rpc.ErrNotificationsUnsupported
   242  	}
   243  
   244  	var (
   245  		rpcSub      = notifier.CreateSubscription()
   246  		matchedLogs = make(chan []*types.Log)
   247  	)
   248  
   249  	logsSub, err := api.events.SubscribeLogs(ethereum.FilterQuery(crit), matchedLogs)
   250  	if err != nil {
   251  		return nil, err
   252  	}
   253  
   254  	go func() {
   255  
   256  		for {
   257  			select {
   258  			case logs := <-matchedLogs:
   259  				for _, log := range logs {
   260  					notifier.Notify(rpcSub.ID, &log)
   261  				}
   262  			case <-rpcSub.Err(): // client send an unsubscribe request
   263  				logsSub.Unsubscribe()
   264  				return
   265  			case <-notifier.Closed(): // connection dropped
   266  				logsSub.Unsubscribe()
   267  				return
   268  			}
   269  		}
   270  	}()
   271  
   272  	return rpcSub, nil
   273  }
   274  
   275  // FilterCriteria represents a request to create a new filter.
   276  // Same as ethereum.FilterQuery but with UnmarshalJSON() method.
   277  type FilterCriteria ethereum.FilterQuery
   278  
   279  // NewFilter creates a new filter and returns the filter id. It can be
   280  // used to retrieve logs when the state changes. This method cannot be
   281  // used to fetch logs that are already stored in the state.
   282  //
   283  // Default criteria for the from and to block are "latest".
   284  // Using "latest" as block number will return logs for mined blocks.
   285  // Using "pending" as block number returns logs for not yet mined (pending) blocks.
   286  // In case logs are removed (chain reorg) previously returned logs are returned
   287  // again but with the removed property set to true.
   288  //
   289  // In case "fromBlock" > "toBlock" an error is returned.
   290  //
   291  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_newfilter
   292  func (api *PublicFilterAPI) NewFilter(crit FilterCriteria) (rpc.ID, error) {
   293  	logs := make(chan []*types.Log)
   294  	logsSub, err := api.events.SubscribeLogs(ethereum.FilterQuery(crit), logs)
   295  	if err != nil {
   296  		return rpc.ID(""), err
   297  	}
   298  
   299  	api.filtersMu.Lock()
   300  	api.filters[logsSub.ID] = &filter{typ: LogsSubscription, crit: crit, deadline: time.NewTimer(deadline), logs: make([]*types.Log, 0), s: logsSub}
   301  	api.filtersMu.Unlock()
   302  
   303  	go func() {
   304  		for {
   305  			select {
   306  			case l := <-logs:
   307  				api.filtersMu.Lock()
   308  				if f, found := api.filters[logsSub.ID]; found {
   309  					f.logs = append(f.logs, l...)
   310  				}
   311  				api.filtersMu.Unlock()
   312  			case <-logsSub.Err():
   313  				api.filtersMu.Lock()
   314  				delete(api.filters, logsSub.ID)
   315  				api.filtersMu.Unlock()
   316  				return
   317  			}
   318  		}
   319  	}()
   320  
   321  	return logsSub.ID, nil
   322  }
   323  
   324  // GetLogs returns logs matching the given argument that are stored within the state.
   325  //
   326  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getlogs
   327  func (api *PublicFilterAPI) GetLogs(ctx context.Context, crit FilterCriteria) ([]*types.Log, error) {
   328  	var filter *Filter
   329  	if crit.BlockHash != nil {
   330  		// Block filter requested, construct a single-shot filter
   331  		filter = NewBlockFilter(api.backend, *crit.BlockHash, crit.Addresses, crit.Topics)
   332  	} else {
   333  		// Convert the RPC block numbers into internal representations
   334  		begin := rpc.LatestBlockNumber.Int64()
   335  		if crit.FromBlock != nil {
   336  			begin = crit.FromBlock.Int64()
   337  		}
   338  		end := rpc.LatestBlockNumber.Int64()
   339  		if crit.ToBlock != nil {
   340  			end = crit.ToBlock.Int64()
   341  		}
   342  		// Construct the range filter
   343  		filter = NewRangeFilter(api.backend, begin, end, crit.Addresses, crit.Topics)
   344  	}
   345  	// Run the filter and return all the logs
   346  	logs, err := filter.Logs(ctx)
   347  	if err != nil {
   348  		return nil, err
   349  	}
   350  	return returnLogs(logs), err
   351  }
   352  
   353  // UninstallFilter removes the filter with the given filter id.
   354  //
   355  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_uninstallfilter
   356  func (api *PublicFilterAPI) UninstallFilter(id rpc.ID) bool {
   357  	api.filtersMu.Lock()
   358  	f, found := api.filters[id]
   359  	if found {
   360  		delete(api.filters, id)
   361  	}
   362  	api.filtersMu.Unlock()
   363  	if found {
   364  		f.s.Unsubscribe()
   365  	}
   366  
   367  	return found
   368  }
   369  
   370  // GetFilterLogs returns the logs for the filter with the given id.
   371  // If the filter could not be found an empty array of logs is returned.
   372  //
   373  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterlogs
   374  func (api *PublicFilterAPI) GetFilterLogs(ctx context.Context, id rpc.ID) ([]*types.Log, error) {
   375  	api.filtersMu.Lock()
   376  	f, found := api.filters[id]
   377  	api.filtersMu.Unlock()
   378  
   379  	if !found || f.typ != LogsSubscription {
   380  		return nil, fmt.Errorf("filter not found")
   381  	}
   382  
   383  	var filter *Filter
   384  	if f.crit.BlockHash != nil {
   385  		// Block filter requested, construct a single-shot filter
   386  		filter = NewBlockFilter(api.backend, *f.crit.BlockHash, f.crit.Addresses, f.crit.Topics)
   387  	} else {
   388  		// Convert the RPC block numbers into internal representations
   389  		begin := rpc.LatestBlockNumber.Int64()
   390  		if f.crit.FromBlock != nil {
   391  			begin = f.crit.FromBlock.Int64()
   392  		}
   393  		end := rpc.LatestBlockNumber.Int64()
   394  		if f.crit.ToBlock != nil {
   395  			end = f.crit.ToBlock.Int64()
   396  		}
   397  		// Construct the range filter
   398  		filter = NewRangeFilter(api.backend, begin, end, f.crit.Addresses, f.crit.Topics)
   399  	}
   400  	// Run the filter and return all the logs
   401  	logs, err := filter.Logs(ctx)
   402  	if err != nil {
   403  		return nil, err
   404  	}
   405  	return returnLogs(logs), nil
   406  }
   407  
   408  // GetFilterChanges returns the logs for the filter with the given id since
   409  // last time it was called. This can be used for polling.
   410  //
   411  // For pending transaction and block filters the result is []common.Hash.
   412  // (pending)Log filters return []Log.
   413  //
   414  // https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterchanges
   415  func (api *PublicFilterAPI) GetFilterChanges(id rpc.ID) (interface{}, error) {
   416  	api.filtersMu.Lock()
   417  	defer api.filtersMu.Unlock()
   418  
   419  	if f, found := api.filters[id]; found {
   420  		if !f.deadline.Stop() {
   421  			// timer expired but filter is not yet removed in timeout loop
   422  			// receive timer value and reset timer
   423  			<-f.deadline.C
   424  		}
   425  		f.deadline.Reset(deadline)
   426  
   427  		switch f.typ {
   428  		case PendingTransactionsSubscription, BlocksSubscription:
   429  			hashes := f.hashes
   430  			f.hashes = nil
   431  			return returnHashes(hashes), nil
   432  		case LogsSubscription:
   433  			logs := f.logs
   434  			f.logs = nil
   435  			return returnLogs(logs), nil
   436  		}
   437  	}
   438  
   439  	return []interface{}{}, fmt.Errorf("filter not found")
   440  }
   441  
   442  // returnHashes is a helper that will return an empty hash array case the given hash array is nil,
   443  // otherwise the given hashes array is returned.
   444  func returnHashes(hashes []common.Hash) []common.Hash {
   445  	if hashes == nil {
   446  		return []common.Hash{}
   447  	}
   448  	return hashes
   449  }
   450  
   451  // returnLogs is a helper that will return an empty log array in case the given logs array is nil,
   452  // otherwise the given logs array is returned.
   453  func returnLogs(logs []*types.Log) []*types.Log {
   454  	if logs == nil {
   455  		return []*types.Log{}
   456  	}
   457  	return logs
   458  }
   459  
   460  // UnmarshalJSON sets *args fields with given data.
   461  func (args *FilterCriteria) UnmarshalJSON(data []byte) error {
   462  	type input struct {
   463  		BlockHash *common.Hash     `json:"blockHash"`
   464  		FromBlock *rpc.BlockNumber `json:"fromBlock"`
   465  		ToBlock   *rpc.BlockNumber `json:"toBlock"`
   466  		Addresses interface{}      `json:"address"`
   467  		Topics    []interface{}    `json:"topics"`
   468  	}
   469  
   470  	var raw input
   471  	if err := json.Unmarshal(data, &raw); err != nil {
   472  		return err
   473  	}
   474  
   475  	if raw.BlockHash != nil {
   476  		if raw.FromBlock != nil || raw.ToBlock != nil {
   477  			// BlockHash is mutually exclusive with FromBlock/ToBlock criteria
   478  			return fmt.Errorf("cannot specify both BlockHash and FromBlock/ToBlock, choose one or the other")
   479  		}
   480  		args.BlockHash = raw.BlockHash
   481  	} else {
   482  		if raw.FromBlock != nil {
   483  			args.FromBlock = big.NewInt(raw.FromBlock.Int64())
   484  		}
   485  
   486  		if raw.ToBlock != nil {
   487  			args.ToBlock = big.NewInt(raw.ToBlock.Int64())
   488  		}
   489  	}
   490  
   491  	args.Addresses = []common.Address{}
   492  
   493  	if raw.Addresses != nil {
   494  		// raw.Address can contain a single address or an array of addresses
   495  		switch rawAddr := raw.Addresses.(type) {
   496  		case []interface{}:
   497  			for i, addr := range rawAddr {
   498  				if strAddr, ok := addr.(string); ok {
   499  					addr, err := decodeAddress(strAddr)
   500  					if err != nil {
   501  						return fmt.Errorf("invalid address at index %d: %v", i, err)
   502  					}
   503  					args.Addresses = append(args.Addresses, addr)
   504  				} else {
   505  					return fmt.Errorf("non-string address at index %d", i)
   506  				}
   507  			}
   508  		case string:
   509  			addr, err := decodeAddress(rawAddr)
   510  			if err != nil {
   511  				return fmt.Errorf("invalid address: %v", err)
   512  			}
   513  			args.Addresses = []common.Address{addr}
   514  		default:
   515  			return errors.New("invalid addresses in query")
   516  		}
   517  	}
   518  
   519  	// topics is an array consisting of strings and/or arrays of strings.
   520  	// JSON null values are converted to common.Hash{} and ignored by the filter manager.
   521  	if len(raw.Topics) > 0 {
   522  		args.Topics = make([][]common.Hash, len(raw.Topics))
   523  		for i, t := range raw.Topics {
   524  			switch topic := t.(type) {
   525  			case nil:
   526  				// ignore topic when matching logs
   527  
   528  			case string:
   529  				// match specific topic
   530  				top, err := decodeTopic(topic)
   531  				if err != nil {
   532  					return err
   533  				}
   534  				args.Topics[i] = []common.Hash{top}
   535  
   536  			case []interface{}:
   537  				// or case e.g. [null, "topic0", "topic1"]
   538  				for _, rawTopic := range topic {
   539  					if rawTopic == nil {
   540  						// null component, match all
   541  						args.Topics[i] = nil
   542  						break
   543  					}
   544  					if topic, ok := rawTopic.(string); ok {
   545  						parsed, err := decodeTopic(topic)
   546  						if err != nil {
   547  							return err
   548  						}
   549  						args.Topics[i] = append(args.Topics[i], parsed)
   550  					} else {
   551  						return fmt.Errorf("invalid topic(s)")
   552  					}
   553  				}
   554  			default:
   555  				return fmt.Errorf("invalid topic(s)")
   556  			}
   557  		}
   558  	}
   559  
   560  	return nil
   561  }
   562  
   563  func decodeAddress(s string) (common.Address, error) {
   564  	b, err := hexutil.Decode(s)
   565  	if err == nil && len(b) != common.AddressLength {
   566  		err = fmt.Errorf("hex has invalid length %d after decoding; expected %d for address", len(b), common.AddressLength)
   567  	}
   568  	return common.BytesToAddress(b), err
   569  }
   570  
   571  func decodeTopic(s string) (common.Hash, error) {
   572  	b, err := hexutil.Decode(s)
   573  	if err == nil && len(b) != common.HashLength {
   574  		err = fmt.Errorf("hex has invalid length %d after decoding; expected %d for topic", len(b), common.HashLength)
   575  	}
   576  	return common.BytesToHash(b), err
   577  }