github.com/aigarnetwork/aigar@v0.0.0-20191115204914-d59a6eb70f8e/whisper/whisperv6/filter.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 whisperv6
    19  
    20  import (
    21  	"crypto/ecdsa"
    22  	"fmt"
    23  	"sync"
    24  
    25  	"github.com/AigarNetwork/aigar/common"
    26  	"github.com/AigarNetwork/aigar/crypto"
    27  	"github.com/AigarNetwork/aigar/log"
    28  )
    29  
    30  // Filter represents a Whisper message filter
    31  type Filter struct {
    32  	Src        *ecdsa.PublicKey  // Sender of the message
    33  	KeyAsym    *ecdsa.PrivateKey // Private Key of recipient
    34  	KeySym     []byte            // Key associated with the Topic
    35  	Topics     [][]byte          // Topics to filter messages with
    36  	PoW        float64           // Proof of work as described in the Whisper spec
    37  	AllowP2P   bool              // Indicates whether this filter is interested in direct peer-to-peer messages
    38  	SymKeyHash common.Hash       // The Keccak256Hash of the symmetric key, needed for optimization
    39  	id         string            // unique identifier
    40  
    41  	Messages map[common.Hash]*ReceivedMessage
    42  	mutex    sync.RWMutex
    43  }
    44  
    45  // Filters represents a collection of filters
    46  type Filters struct {
    47  	watchers map[string]*Filter
    48  
    49  	topicMatcher     map[TopicType]map[*Filter]struct{} // map a topic to the filters that are interested in being notified when a message matches that topic
    50  	allTopicsMatcher map[*Filter]struct{}               // list all the filters that will be notified of a new message, no matter what its topic is
    51  
    52  	whisper *Whisper
    53  	mutex   sync.RWMutex
    54  }
    55  
    56  // NewFilters returns a newly created filter collection
    57  func NewFilters(w *Whisper) *Filters {
    58  	return &Filters{
    59  		watchers:         make(map[string]*Filter),
    60  		topicMatcher:     make(map[TopicType]map[*Filter]struct{}),
    61  		allTopicsMatcher: make(map[*Filter]struct{}),
    62  		whisper:          w,
    63  	}
    64  }
    65  
    66  // Install will add a new filter to the filter collection
    67  func (fs *Filters) Install(watcher *Filter) (string, error) {
    68  	if watcher.KeySym != nil && watcher.KeyAsym != nil {
    69  		return "", fmt.Errorf("filters must choose between symmetric and asymmetric keys")
    70  	}
    71  
    72  	if watcher.Messages == nil {
    73  		watcher.Messages = make(map[common.Hash]*ReceivedMessage)
    74  	}
    75  
    76  	id, err := GenerateRandomID()
    77  	if err != nil {
    78  		return "", err
    79  	}
    80  
    81  	fs.mutex.Lock()
    82  	defer fs.mutex.Unlock()
    83  
    84  	if fs.watchers[id] != nil {
    85  		return "", fmt.Errorf("failed to generate unique ID")
    86  	}
    87  
    88  	if watcher.expectsSymmetricEncryption() {
    89  		watcher.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym)
    90  	}
    91  
    92  	watcher.id = id
    93  	fs.watchers[id] = watcher
    94  	fs.addTopicMatcher(watcher)
    95  	return id, err
    96  }
    97  
    98  // Uninstall will remove a filter whose id has been specified from
    99  // the filter collection
   100  func (fs *Filters) Uninstall(id string) bool {
   101  	fs.mutex.Lock()
   102  	defer fs.mutex.Unlock()
   103  	if fs.watchers[id] != nil {
   104  		fs.removeFromTopicMatchers(fs.watchers[id])
   105  		delete(fs.watchers, id)
   106  		return true
   107  	}
   108  	return false
   109  }
   110  
   111  // addTopicMatcher adds a filter to the topic matchers.
   112  // If the filter's Topics array is empty, it will be tried on every topic.
   113  // Otherwise, it will be tried on the topics specified.
   114  func (fs *Filters) addTopicMatcher(watcher *Filter) {
   115  	if len(watcher.Topics) == 0 {
   116  		fs.allTopicsMatcher[watcher] = struct{}{}
   117  	} else {
   118  		for _, t := range watcher.Topics {
   119  			topic := BytesToTopic(t)
   120  			if fs.topicMatcher[topic] == nil {
   121  				fs.topicMatcher[topic] = make(map[*Filter]struct{})
   122  			}
   123  			fs.topicMatcher[topic][watcher] = struct{}{}
   124  		}
   125  	}
   126  }
   127  
   128  // removeFromTopicMatchers removes a filter from the topic matchers
   129  func (fs *Filters) removeFromTopicMatchers(watcher *Filter) {
   130  	delete(fs.allTopicsMatcher, watcher)
   131  	for _, topic := range watcher.Topics {
   132  		delete(fs.topicMatcher[BytesToTopic(topic)], watcher)
   133  	}
   134  }
   135  
   136  // getWatchersByTopic returns a slice containing the filters that
   137  // match a specific topic
   138  func (fs *Filters) getWatchersByTopic(topic TopicType) []*Filter {
   139  	res := make([]*Filter, 0, len(fs.allTopicsMatcher))
   140  	for watcher := range fs.allTopicsMatcher {
   141  		res = append(res, watcher)
   142  	}
   143  	for watcher := range fs.topicMatcher[topic] {
   144  		res = append(res, watcher)
   145  	}
   146  	return res
   147  }
   148  
   149  // Get returns a filter from the collection with a specific ID
   150  func (fs *Filters) Get(id string) *Filter {
   151  	fs.mutex.RLock()
   152  	defer fs.mutex.RUnlock()
   153  	return fs.watchers[id]
   154  }
   155  
   156  // NotifyWatchers notifies any filter that has declared interest
   157  // for the envelope's topic.
   158  func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
   159  	var msg *ReceivedMessage
   160  
   161  	fs.mutex.RLock()
   162  	defer fs.mutex.RUnlock()
   163  
   164  	candidates := fs.getWatchersByTopic(env.Topic)
   165  	for _, watcher := range candidates {
   166  		if p2pMessage && !watcher.AllowP2P {
   167  			log.Trace(fmt.Sprintf("msg [%x], filter [%s]: p2p messages are not allowed", env.Hash(), watcher.id))
   168  			continue
   169  		}
   170  
   171  		var match bool
   172  		if msg != nil {
   173  			match = watcher.MatchMessage(msg)
   174  		} else {
   175  			match = watcher.MatchEnvelope(env)
   176  			if match {
   177  				msg = env.Open(watcher)
   178  				if msg == nil {
   179  					log.Trace("processing message: failed to open", "message", env.Hash().Hex(), "filter", watcher.id)
   180  				}
   181  			} else {
   182  				log.Trace("processing message: does not match", "message", env.Hash().Hex(), "filter", watcher.id)
   183  			}
   184  		}
   185  
   186  		if match && msg != nil {
   187  			log.Trace("processing message: decrypted", "hash", env.Hash().Hex())
   188  			if watcher.Src == nil || IsPubKeyEqual(msg.Src, watcher.Src) {
   189  				watcher.Trigger(msg)
   190  			}
   191  		}
   192  	}
   193  }
   194  
   195  func (f *Filter) expectsAsymmetricEncryption() bool {
   196  	return f.KeyAsym != nil
   197  }
   198  
   199  func (f *Filter) expectsSymmetricEncryption() bool {
   200  	return f.KeySym != nil
   201  }
   202  
   203  // Trigger adds a yet-unknown message to the filter's list of
   204  // received messages.
   205  func (f *Filter) Trigger(msg *ReceivedMessage) {
   206  	f.mutex.Lock()
   207  	defer f.mutex.Unlock()
   208  
   209  	if _, exist := f.Messages[msg.EnvelopeHash]; !exist {
   210  		f.Messages[msg.EnvelopeHash] = msg
   211  	}
   212  }
   213  
   214  // Retrieve will return the list of all received messages associated
   215  // to a filter.
   216  func (f *Filter) Retrieve() (all []*ReceivedMessage) {
   217  	f.mutex.Lock()
   218  	defer f.mutex.Unlock()
   219  
   220  	all = make([]*ReceivedMessage, 0, len(f.Messages))
   221  	for _, msg := range f.Messages {
   222  		all = append(all, msg)
   223  	}
   224  
   225  	f.Messages = make(map[common.Hash]*ReceivedMessage) // delete old messages
   226  	return all
   227  }
   228  
   229  // MatchMessage checks if the filter matches an already decrypted
   230  // message (i.e. a Message that has already been handled by
   231  // MatchEnvelope when checked by a previous filter).
   232  // Topics are not checked here, since this is done by topic matchers.
   233  func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
   234  	if f.PoW > 0 && msg.PoW < f.PoW {
   235  		return false
   236  	}
   237  
   238  	if f.expectsAsymmetricEncryption() && msg.isAsymmetricEncryption() {
   239  		return IsPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst)
   240  	} else if f.expectsSymmetricEncryption() && msg.isSymmetricEncryption() {
   241  		return f.SymKeyHash == msg.SymKeyHash
   242  	}
   243  	return false
   244  }
   245  
   246  // MatchEnvelope checks if it's worth decrypting the message. If
   247  // it returns `true`, client code is expected to attempt decrypting
   248  // the message and subsequently call MatchMessage.
   249  // Topics are not checked here, since this is done by topic matchers.
   250  func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
   251  	return f.PoW <= 0 || envelope.pow >= f.PoW
   252  }
   253  
   254  // IsPubKeyEqual checks that two public keys are equal
   255  func IsPubKeyEqual(a, b *ecdsa.PublicKey) bool {
   256  	if !ValidatePublicKey(a) {
   257  		return false
   258  	} else if !ValidatePublicKey(b) {
   259  		return false
   260  	}
   261  	// the curve is always the same, just compare the points
   262  	return a.X.Cmp(b.X) == 0 && a.Y.Cmp(b.Y) == 0
   263  }