filter.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. // Copyright 2016 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. package whisperv5
  17. import (
  18. "crypto/ecdsa"
  19. "fmt"
  20. "sync"
  21. "github.com/ethereum/go-ethereum/common"
  22. "github.com/ethereum/go-ethereum/crypto"
  23. "github.com/ethereum/go-ethereum/log"
  24. )
  25. type Filter struct {
  26. Src *ecdsa.PublicKey // Sender of the message
  27. KeyAsym *ecdsa.PrivateKey // Private Key of recipient
  28. KeySym []byte // Key associated with the Topic
  29. Topics [][]byte // Topics to filter messages with
  30. PoW float64 // Proof of work as described in the Whisper spec
  31. AllowP2P bool // Indicates whether this filter is interested in direct peer-to-peer messages
  32. SymKeyHash common.Hash // The Keccak256Hash of the symmetric key, needed for optimization
  33. Messages map[common.Hash]*ReceivedMessage
  34. mutex sync.RWMutex
  35. }
  36. type Filters struct {
  37. watchers map[string]*Filter
  38. whisper *Whisper
  39. mutex sync.RWMutex
  40. }
  41. func NewFilters(w *Whisper) *Filters {
  42. return &Filters{
  43. watchers: make(map[string]*Filter),
  44. whisper: w,
  45. }
  46. }
  47. func (fs *Filters) Install(watcher *Filter) (string, error) {
  48. if watcher.Messages == nil {
  49. watcher.Messages = make(map[common.Hash]*ReceivedMessage)
  50. }
  51. id, err := GenerateRandomID()
  52. if err != nil {
  53. return "", err
  54. }
  55. fs.mutex.Lock()
  56. defer fs.mutex.Unlock()
  57. if fs.watchers[id] != nil {
  58. return "", fmt.Errorf("failed to generate unique ID")
  59. }
  60. if watcher.expectsSymmetricEncryption() {
  61. watcher.SymKeyHash = crypto.Keccak256Hash(watcher.KeySym)
  62. }
  63. fs.watchers[id] = watcher
  64. return id, err
  65. }
  66. func (fs *Filters) Uninstall(id string) bool {
  67. fs.mutex.Lock()
  68. defer fs.mutex.Unlock()
  69. if fs.watchers[id] != nil {
  70. delete(fs.watchers, id)
  71. return true
  72. }
  73. return false
  74. }
  75. func (fs *Filters) Get(id string) *Filter {
  76. fs.mutex.RLock()
  77. defer fs.mutex.RUnlock()
  78. return fs.watchers[id]
  79. }
  80. func (fs *Filters) NotifyWatchers(env *Envelope, p2pMessage bool) {
  81. var msg *ReceivedMessage
  82. fs.mutex.RLock()
  83. defer fs.mutex.RUnlock()
  84. i := -1 // only used for logging info
  85. for _, watcher := range fs.watchers {
  86. i++
  87. if p2pMessage && !watcher.AllowP2P {
  88. log.Trace(fmt.Sprintf("msg [%x], filter [%d]: p2p messages are not allowed", env.Hash(), i))
  89. continue
  90. }
  91. var match bool
  92. if msg != nil {
  93. match = watcher.MatchMessage(msg)
  94. } else {
  95. match = watcher.MatchEnvelope(env)
  96. if match {
  97. msg = env.Open(watcher)
  98. if msg == nil {
  99. log.Trace("processing message: failed to open", "message", env.Hash().Hex(), "filter", i)
  100. }
  101. } else {
  102. log.Trace("processing message: does not match", "message", env.Hash().Hex(), "filter", i)
  103. }
  104. }
  105. if match && msg != nil {
  106. log.Trace("processing message: decrypted", "hash", env.Hash().Hex())
  107. if watcher.Src == nil || IsPubKeyEqual(msg.Src, watcher.Src) {
  108. watcher.Trigger(msg)
  109. }
  110. }
  111. }
  112. }
  113. func (f *Filter) processEnvelope(env *Envelope) *ReceivedMessage {
  114. if f.MatchEnvelope(env) {
  115. msg := env.Open(f)
  116. if msg != nil {
  117. return msg
  118. } else {
  119. log.Trace("processing envelope: failed to open", "hash", env.Hash().Hex())
  120. }
  121. } else {
  122. log.Trace("processing envelope: does not match", "hash", env.Hash().Hex())
  123. }
  124. return nil
  125. }
  126. func (f *Filter) expectsAsymmetricEncryption() bool {
  127. return f.KeyAsym != nil
  128. }
  129. func (f *Filter) expectsSymmetricEncryption() bool {
  130. return f.KeySym != nil
  131. }
  132. func (f *Filter) Trigger(msg *ReceivedMessage) {
  133. f.mutex.Lock()
  134. defer f.mutex.Unlock()
  135. if _, exist := f.Messages[msg.EnvelopeHash]; !exist {
  136. f.Messages[msg.EnvelopeHash] = msg
  137. }
  138. }
  139. func (f *Filter) Retrieve() (all []*ReceivedMessage) {
  140. f.mutex.Lock()
  141. defer f.mutex.Unlock()
  142. all = make([]*ReceivedMessage, 0, len(f.Messages))
  143. for _, msg := range f.Messages {
  144. all = append(all, msg)
  145. }
  146. f.Messages = make(map[common.Hash]*ReceivedMessage) // delete old messages
  147. return all
  148. }
  149. func (f *Filter) MatchMessage(msg *ReceivedMessage) bool {
  150. if f.PoW > 0 && msg.PoW < f.PoW {
  151. return false
  152. }
  153. if f.expectsAsymmetricEncryption() && msg.isAsymmetricEncryption() {
  154. return IsPubKeyEqual(&f.KeyAsym.PublicKey, msg.Dst) && f.MatchTopic(msg.Topic)
  155. } else if f.expectsSymmetricEncryption() && msg.isSymmetricEncryption() {
  156. return f.SymKeyHash == msg.SymKeyHash && f.MatchTopic(msg.Topic)
  157. }
  158. return false
  159. }
  160. func (f *Filter) MatchEnvelope(envelope *Envelope) bool {
  161. if f.PoW > 0 && envelope.pow < f.PoW {
  162. return false
  163. }
  164. if f.expectsAsymmetricEncryption() && envelope.isAsymmetric() {
  165. return f.MatchTopic(envelope.Topic)
  166. } else if f.expectsSymmetricEncryption() && envelope.IsSymmetric() {
  167. return f.MatchTopic(envelope.Topic)
  168. }
  169. return false
  170. }
  171. func (f *Filter) MatchTopic(topic TopicType) bool {
  172. if len(f.Topics) == 0 {
  173. // any topic matches
  174. return true
  175. }
  176. for _, bt := range f.Topics {
  177. if matchSingleTopic(topic, bt) {
  178. return true
  179. }
  180. }
  181. return false
  182. }
  183. func matchSingleTopic(topic TopicType, bt []byte) bool {
  184. if len(bt) > TopicLength {
  185. bt = bt[:TopicLength]
  186. }
  187. if len(bt) < TopicLength {
  188. return false
  189. }
  190. for j, b := range bt {
  191. if topic[j] != b {
  192. return false
  193. }
  194. }
  195. return true
  196. }
  197. func IsPubKeyEqual(a, b *ecdsa.PublicKey) bool {
  198. if !ValidatePublicKey(a) {
  199. return false
  200. } else if !ValidatePublicKey(b) {
  201. return false
  202. }
  203. // the curve is always the same, just compare the points
  204. return a.X.Cmp(b.X) == 0 && a.Y.Cmp(b.Y) == 0
  205. }