forked from status-im/status-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0004-whisper-notifications.patch
1218 lines (1197 loc) · 39.3 KB
/
0004-whisper-notifications.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
diff --git a/whisper/notifications/discovery.go b/whisper/notifications/discovery.go
new file mode 100644
index 000000000..de8ec85be
--- /dev/null
+++ b/whisper/notifications/discovery.go
@@ -0,0 +1,154 @@
+package notifications
+
+import (
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/log"
+ whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
+)
+
+const (
+ topicDiscoverServer = "DISCOVER_NOTIFICATION_SERVER"
+ topicProposeServer = "PROPOSE_NOTIFICATION_SERVER"
+ topicServerAccepted = "ACCEPT_NOTIFICATION_SERVER"
+ topicAckClientSubscription = "ACK_NOTIFICATION_SERVER_SUBSCRIPTION"
+)
+
+// discoveryService abstract notification server discovery protocol
+type discoveryService struct {
+ server *NotificationServer
+
+ discoverFilterID string
+ serverAcceptedFilterID string
+}
+
+// messageProcessingFn is a callback used to process incoming client requests
+type messageProcessingFn func(*whisper.ReceivedMessage) error
+
+func NewDiscoveryService(notificationServer *NotificationServer) *discoveryService {
+ return &discoveryService{
+ server: notificationServer,
+ }
+}
+
+// Start installs necessary filters to watch for incoming discovery requests,
+// then in separate routine starts watcher loop
+func (s *discoveryService) Start() error {
+ var err error
+
+ // notification server discovery requests
+ s.discoverFilterID, err = s.server.installKeyFilter(topicDiscoverServer, s.server.protocolKey)
+ if err != nil {
+ return fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.server.requestProcessorLoop(s.discoverFilterID, topicDiscoverServer, s.processDiscoveryRequest)
+
+ // notification server accept/select requests
+ s.serverAcceptedFilterID, err = s.server.installKeyFilter(topicServerAccepted, s.server.protocolKey)
+ if err != nil {
+ return fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.server.requestProcessorLoop(s.serverAcceptedFilterID, topicServerAccepted, s.processServerAcceptedRequest)
+
+ log.Info("notification server discovery service started")
+ return nil
+}
+
+// Stop stops all discovery processing loops
+func (s *discoveryService) Stop() error {
+ s.server.whisper.Unsubscribe(s.discoverFilterID)
+ s.server.whisper.Unsubscribe(s.serverAcceptedFilterID)
+
+ log.Info("notification server discovery service stopped")
+ return nil
+}
+
+// processDiscoveryRequest processes incoming client requests of type:
+// when client tries to discover suitable notification server
+func (s *discoveryService) processDiscoveryRequest(msg *whisper.ReceivedMessage) error {
+ // offer this node as notification server
+ msgParams := whisper.MessageParams{
+ Src: s.server.protocolKey,
+ Dst: msg.Src,
+ Topic: MakeTopic([]byte(topicProposeServer)),
+ Payload: []byte(`{"server": "0x` + s.server.nodeID + `"}`),
+ TTL: uint32(s.server.config.TTL),
+ PoW: s.server.config.MinimumPoW,
+ WorkTime: 5,
+ }
+ response, err := whisper.NewSentMessage(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to create proposal message: %v", err)
+ }
+ env, err := response.Wrap(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to wrap server proposal message: %v", err)
+ }
+
+ if err := s.server.whisper.Send(env); err != nil {
+ return fmt.Errorf("failed to send server proposal message: %v", err)
+ }
+
+ log.Info(fmt.Sprintf("server proposal sent (server: %v, dst: %v, topic: %x)",
+ s.server.nodeID, common.ToHex(crypto.FromECDSAPub(msgParams.Dst)), msgParams.Topic))
+ return nil
+}
+
+// processServerAcceptedRequest processes incoming client requests of type:
+// when client is ready to select the given node as its notification server
+func (s *discoveryService) processServerAcceptedRequest(msg *whisper.ReceivedMessage) error {
+ var parsedMessage struct {
+ ServerID string `json:"server"`
+ }
+ if err := json.Unmarshal(msg.Payload, &parsedMessage); err != nil {
+ return err
+ }
+
+ if msg.Src == nil {
+ return errors.New("message 'from' field is required")
+ }
+
+ // make sure that only requests made to the current node are processed
+ if parsedMessage.ServerID != `0x`+s.server.nodeID {
+ return nil
+ }
+
+ // register client
+ sessionKey, err := s.server.RegisterClientSession(&ClientSession{
+ ClientKey: hex.EncodeToString(crypto.FromECDSAPub(msg.Src)),
+ })
+ if err != nil {
+ return err
+ }
+
+ // confirm that client has been successfully subscribed
+ msgParams := whisper.MessageParams{
+ Src: s.server.protocolKey,
+ Dst: msg.Src,
+ Topic: MakeTopic([]byte(topicAckClientSubscription)),
+ Payload: []byte(`{"server": "0x` + s.server.nodeID + `", "key": "0x` + hex.EncodeToString(sessionKey) + `"}`),
+ TTL: uint32(s.server.config.TTL),
+ PoW: s.server.config.MinimumPoW,
+ WorkTime: 5,
+ }
+ response, err := whisper.NewSentMessage(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to create server proposal message: %v", err)
+ }
+ env, err := response.Wrap(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to wrap server proposal message: %v", err)
+ }
+
+ if err := s.server.whisper.Send(env); err != nil {
+ return fmt.Errorf("failed to send server proposal message: %v", err)
+ }
+
+ log.Info(fmt.Sprintf("server confirms client subscription (dst: %v, topic: %x)", msgParams.Dst, msgParams.Topic))
+ return nil
+}
diff --git a/whisper/notifications/provider.go b/whisper/notifications/provider.go
new file mode 100644
index 000000000..032463a6e
--- /dev/null
+++ b/whisper/notifications/provider.go
@@ -0,0 +1,59 @@
+package notifications
+
+import (
+ "bytes"
+ "fmt"
+ "io/ioutil"
+ "net/http"
+ "strings"
+
+ "github.com/ethereum/go-ethereum/log"
+ "github.com/status-im/status-go/geth/params"
+)
+
+// NotificationDeliveryProvider handles the notification delivery
+type NotificationDeliveryProvider interface {
+ Send(id string, payload string) error
+}
+
+// FirebaseProvider represents FCM provider
+type FirebaseProvider struct {
+ AuthorizationKey string
+ NotificationTriggerURL string
+}
+
+// NewFirebaseProvider creates new FCM provider
+func NewFirebaseProvider(config *params.FirebaseConfig) *FirebaseProvider {
+ authorizationKey, _ := config.ReadAuthorizationKeyFile()
+ return &FirebaseProvider{
+ NotificationTriggerURL: config.NotificationTriggerURL,
+ AuthorizationKey: string(authorizationKey),
+ }
+}
+
+// Send triggers sending of Push Notification to a given device id
+func (p *FirebaseProvider) Send(id string, payload string) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ err = fmt.Errorf("panic: %v", r)
+ }
+ }()
+
+ jsonRequest := strings.Replace(payload, "{{ ID }}", id, 3)
+ req, err := http.NewRequest("POST", p.NotificationTriggerURL, bytes.NewBuffer([]byte(jsonRequest)))
+ req.Header.Set("Authorization", "key="+p.AuthorizationKey)
+ req.Header.Set("Content-Type", "application/json")
+
+ client := &http.Client{}
+ resp, err := client.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ log.Debug("FCM response", "status", resp.Status, "header", resp.Header)
+ body, _ := ioutil.ReadAll(resp.Body)
+ log.Debug("FCM response body", "body", string(body))
+
+ return nil
+}
diff --git a/whisper/notifications/server.go b/whisper/notifications/server.go
new file mode 100644
index 000000000..7f27f0301
--- /dev/null
+++ b/whisper/notifications/server.go
@@ -0,0 +1,590 @@
+package notifications
+
+import (
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ "crypto/ecdsa"
+ "encoding/hex"
+ "encoding/json"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/crypto"
+ "github.com/ethereum/go-ethereum/log"
+ "github.com/ethereum/go-ethereum/p2p"
+ whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
+ "github.com/status-im/status-go/geth/params"
+)
+
+const (
+ topicSendNotification = "SEND_NOTIFICATION"
+ topicNewChatSession = "NEW_CHAT_SESSION"
+ topicAckNewChatSession = "ACK_NEW_CHAT_SESSION"
+ topicNewDeviceRegistration = "NEW_DEVICE_REGISTRATION"
+ topicAckDeviceRegistration = "ACK_DEVICE_REGISTRATION"
+ topicCheckClientSession = "CHECK_CLIENT_SESSION"
+ topicConfirmClientSession = "CONFIRM_CLIENT_SESSION"
+ topicDropClientSession = "DROP_CLIENT_SESSION"
+)
+
+var (
+ ErrServiceInitError = errors.New("notification service has not been properly initialized")
+)
+
+// NotificationServer service capable of handling Push Notifications
+type NotificationServer struct {
+ whisper *whisper.Whisper
+ config *params.WhisperConfig
+
+ nodeID string // proposed server will feature this ID
+ discovery *discoveryService // discovery service handles client/server negotiation, when server is selected
+ protocolKey *ecdsa.PrivateKey // private key of service, used to encode handshake communication
+
+ clientSessions map[string]*ClientSession
+ clientSessionsMu sync.RWMutex
+
+ chatSessions map[string]*ChatSession
+ chatSessionsMu sync.RWMutex
+
+ deviceSubscriptions map[string]*DeviceSubscription
+ deviceSubscriptionsMu sync.RWMutex
+
+ firebaseProvider NotificationDeliveryProvider
+
+ quit chan struct{}
+}
+
+// ClientSession abstracts notification client, which expects notifications whenever
+// some envelope can be decoded with session key (key hash is compared for optimization)
+type ClientSession struct {
+ ClientKey string // public key uniquely identifying a client
+ SessionKey []byte // actual symkey used for client - server communication
+ SessionKeyHash common.Hash // The Keccak256Hash of the symmetric key, which is shared between server/client
+ SessionKeyInput []byte // raw symkey used as input for actual SessionKey
+}
+
+// ChatSession abstracts chat session, which some previously registered client can create.
+// ChatSession is used by client for sharing common secret, allowing others to register
+// themselves and eventually to trigger notifications.
+type ChatSession struct {
+ ParentKey string // public key uniquely identifying a client session used to create a chat session
+ ChatKey string // ID that uniquely identifies a chat session
+ SessionKey []byte // actual symkey used for client - server communication
+ SessionKeyHash common.Hash // The Keccak256Hash of the symmetric key, which is shared between server/client
+}
+
+// DeviceSubscription stores enough information about a device (or group of devices),
+// so that Notification Server can trigger notification on that device(s)
+type DeviceSubscription struct {
+ DeviceID string // ID that will be used as destination
+ ChatSessionKeyHash common.Hash // The Keccak256Hash of the symmetric key, which is shared between server/client
+ PubKey *ecdsa.PublicKey // public key of subscriber (to filter out when notification is triggered)
+}
+
+// Init used for service initialization, making sure it is safe to call Start()
+func (s *NotificationServer) Init(whisperService *whisper.Whisper, whisperConfig *params.WhisperConfig) {
+ s.whisper = whisperService
+ s.config = whisperConfig
+
+ s.discovery = NewDiscoveryService(s)
+ s.clientSessions = make(map[string]*ClientSession)
+ s.chatSessions = make(map[string]*ChatSession)
+ s.deviceSubscriptions = make(map[string]*DeviceSubscription)
+ s.quit = make(chan struct{})
+
+ // setup providers (FCM only, for now)
+ s.firebaseProvider = NewFirebaseProvider(whisperConfig.FirebaseConfig)
+}
+
+// Start begins notification loop, in a separate go routine
+func (s *NotificationServer) Start(stack *p2p.Server) error {
+ if s.whisper == nil {
+ return ErrServiceInitError
+ }
+
+ // configure nodeID
+ if stack != nil {
+ if nodeInfo := stack.NodeInfo(); nodeInfo != nil {
+ s.nodeID = nodeInfo.ID
+ }
+ }
+
+ // configure keys
+ identity, err := s.config.ReadIdentityFile()
+ if err != nil {
+ return err
+ }
+ s.whisper.AddKeyPair(identity)
+ s.protocolKey = identity
+ log.Info("protocol pubkey", "key", common.ToHex(crypto.FromECDSAPub(&s.protocolKey.PublicKey)))
+
+ // start discovery protocol
+ s.discovery.Start()
+
+ // client session status requests
+ clientSessionStatusFilterID, err := s.installKeyFilter(topicCheckClientSession, s.protocolKey)
+ if err != nil {
+ return fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.requestProcessorLoop(clientSessionStatusFilterID, topicDiscoverServer, s.processClientSessionStatusRequest)
+
+ // client session remove requests
+ dropClientSessionFilterID, err := s.installKeyFilter(topicDropClientSession, s.protocolKey)
+ if err != nil {
+ return fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.requestProcessorLoop(dropClientSessionFilterID, topicDropClientSession, s.processDropClientSessionRequest)
+
+ log.Info("Whisper Notification Server started")
+ return nil
+}
+
+// Stop handles stopping the running notification loop, and all related resources
+func (s *NotificationServer) Stop() error {
+ close(s.quit)
+
+ if s.whisper == nil {
+ return ErrServiceInitError
+ }
+
+ if s.discovery != nil {
+ s.discovery.Stop()
+ }
+
+ log.Info("Whisper Notification Server stopped")
+ return nil
+}
+
+// RegisterClientSession forms a cryptographic link between server and client.
+// It does so by sharing a session SymKey and installing filter listening for messages
+// encrypted with that key. So, both server and client have a secure way to communicate.
+func (s *NotificationServer) RegisterClientSession(session *ClientSession) (sessionKey []byte, err error) {
+ s.clientSessionsMu.Lock()
+ defer s.clientSessionsMu.Unlock()
+
+ // generate random symmetric session key
+ keyName := fmt.Sprintf("%s-%s", "ntfy-client", crypto.Keccak256Hash([]byte(session.ClientKey)).Hex())
+ sessionKey, sessionKeyDerived, err := s.makeSessionKey(keyName)
+ if err != nil {
+ return nil, err
+ }
+
+ // populate session key hash (will be used to match decrypted message to a given client id)
+ session.SessionKeyInput = sessionKey
+ session.SessionKeyHash = crypto.Keccak256Hash(sessionKeyDerived)
+ session.SessionKey = sessionKeyDerived
+
+ // append to list of known clients
+ // so that it is trivial to go key hash -> client session info
+ id := session.SessionKeyHash.Hex()
+ s.clientSessions[id] = session
+
+ // setup filter, which will get all incoming messages, that are encrypted with SymKey
+ filterID, err := s.installTopicFilter(topicNewChatSession, sessionKeyDerived)
+ if err != nil {
+ return nil, fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.requestProcessorLoop(filterID, topicNewChatSession, s.processNewChatSessionRequest)
+ return
+}
+
+// RegisterChatSession forms a cryptographic link between server and client.
+// This link is meant to be shared with other clients, so that they can use
+// the shared SymKey to trigger notifications for devices attached to a given
+// chat session.
+func (s *NotificationServer) RegisterChatSession(session *ChatSession) (sessionKey []byte, err error) {
+ s.chatSessionsMu.Lock()
+ defer s.chatSessionsMu.Unlock()
+
+ // generate random symmetric session key
+ keyName := fmt.Sprintf("%s-%s", "ntfy-chat", crypto.Keccak256Hash([]byte(session.ParentKey+session.ChatKey)).Hex())
+ sessionKey, sessionKeyDerived, err := s.makeSessionKey(keyName)
+ if err != nil {
+ return nil, err
+ }
+
+ // populate session key hash (will be used to match decrypted message to a given client id)
+ session.SessionKeyHash = crypto.Keccak256Hash(sessionKeyDerived)
+ session.SessionKey = sessionKeyDerived
+
+ // append to list of known clients
+ // so that it is trivial to go key hash -> client session info
+ id := session.SessionKeyHash.Hex()
+ s.chatSessions[id] = session
+
+ // setup filter, to process incoming device registration requests
+ filterID1, err := s.installTopicFilter(topicNewDeviceRegistration, sessionKeyDerived)
+ if err != nil {
+ return nil, fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.requestProcessorLoop(filterID1, topicNewDeviceRegistration, s.processNewDeviceRegistrationRequest)
+
+ // setup filter, to process incoming notification trigger requests
+ filterID2, err := s.installTopicFilter(topicSendNotification, sessionKeyDerived)
+ if err != nil {
+ return nil, fmt.Errorf("failed installing filter: %v", err)
+ }
+ go s.requestProcessorLoop(filterID2, topicSendNotification, s.processSendNotificationRequest)
+
+ return
+}
+
+// RegisterDeviceSubscription persists device id, so that it can be used to trigger notifications.
+func (s *NotificationServer) RegisterDeviceSubscription(subscription *DeviceSubscription) error {
+ s.deviceSubscriptionsMu.Lock()
+ defer s.deviceSubscriptionsMu.Unlock()
+
+ // if one passes the same id again, we will just overwrite
+ id := fmt.Sprintf("%s-%s", "ntfy-device",
+ crypto.Keccak256Hash([]byte(subscription.ChatSessionKeyHash.Hex()+subscription.DeviceID)).Hex())
+ s.deviceSubscriptions[id] = subscription
+
+ log.Info("device registered", "device", subscription.DeviceID)
+ return nil
+}
+
+// DropClientSession uninstalls session
+func (s *NotificationServer) DropClientSession(id string) {
+ dropChatSessions := func(parentKey string) {
+ s.chatSessionsMu.Lock()
+ defer s.chatSessionsMu.Unlock()
+
+ for key, chatSession := range s.chatSessions {
+ if chatSession.ParentKey == parentKey {
+ delete(s.chatSessions, key)
+ log.Info("drop chat session", "key", key)
+ }
+ }
+ }
+
+ dropDeviceSubscriptions := func(parentKey string) {
+ s.deviceSubscriptionsMu.Lock()
+ defer s.deviceSubscriptionsMu.Unlock()
+
+ for key, subscription := range s.deviceSubscriptions {
+ if hex.EncodeToString(crypto.FromECDSAPub(subscription.PubKey)) == parentKey {
+ delete(s.deviceSubscriptions, key)
+ log.Info("drop device subscription", "key", key)
+ }
+ }
+ }
+
+ s.clientSessionsMu.Lock()
+ if session, ok := s.clientSessions[id]; ok {
+ delete(s.clientSessions, id)
+ log.Info("server drops client session", "id", id)
+ s.clientSessionsMu.Unlock()
+
+ dropDeviceSubscriptions(session.ClientKey)
+ dropChatSessions(session.ClientKey)
+ }
+}
+
+// processNewChatSessionRequest processes incoming client requests of type:
+// client has a session key, and ready to create a new chat session (which is
+// a bag of subscribed devices, basically)
+func (s *NotificationServer) processNewChatSessionRequest(msg *whisper.ReceivedMessage) error {
+ s.clientSessionsMu.RLock()
+ defer s.clientSessionsMu.RUnlock()
+
+ var parsedMessage struct {
+ ChatID string `json:"chat"`
+ }
+ if err := json.Unmarshal(msg.Payload, &parsedMessage); err != nil {
+ return err
+ }
+
+ if msg.Src == nil {
+ return errors.New("message 'from' field is required")
+ }
+
+ clientSession, ok := s.clientSessions[msg.SymKeyHash.Hex()]
+ if !ok {
+ return errors.New("client session not found")
+ }
+
+ // register chat session
+ parentKey := hex.EncodeToString(crypto.FromECDSAPub(msg.Src))
+ sessionKey, err := s.RegisterChatSession(&ChatSession{
+ ParentKey: parentKey,
+ ChatKey: parsedMessage.ChatID,
+ })
+ if err != nil {
+ return err
+ }
+
+ // confirm that chat has been successfully created
+ msgParams := whisper.MessageParams{
+ Dst: msg.Src,
+ KeySym: clientSession.SessionKey,
+ Topic: MakeTopic([]byte(topicAckNewChatSession)),
+ Payload: []byte(`{"server": "0x` + s.nodeID + `", "key": "0x` + hex.EncodeToString(sessionKey) + `"}`),
+ TTL: uint32(s.config.TTL),
+ PoW: s.config.MinimumPoW,
+ WorkTime: 5,
+ }
+ response, err := whisper.NewSentMessage(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to create server response message: %v", err)
+ }
+ env, err := response.Wrap(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to wrap server response message: %v", err)
+ }
+
+ if err := s.whisper.Send(env); err != nil {
+ return fmt.Errorf("failed to send server response message: %v", err)
+ }
+
+ log.Info("server confirms chat creation", "dst",
+ common.ToHex(crypto.FromECDSAPub(msgParams.Dst)), "topic", msgParams.Topic.String())
+ return nil
+}
+
+// processNewDeviceRegistrationRequest processes incoming client requests of type:
+// client has a session key, creates chat, and obtains chat SymKey (to be shared with
+// others). Then using that chat SymKey client registers it's device ID with server.
+func (s *NotificationServer) processNewDeviceRegistrationRequest(msg *whisper.ReceivedMessage) error {
+ s.chatSessionsMu.RLock()
+ defer s.chatSessionsMu.RUnlock()
+
+ var parsedMessage struct {
+ DeviceID string `json:"device"`
+ }
+ if err := json.Unmarshal(msg.Payload, &parsedMessage); err != nil {
+ return err
+ }
+
+ if msg.Src == nil {
+ return errors.New("message 'from' field is required")
+ }
+
+ chatSession, ok := s.chatSessions[msg.SymKeyHash.Hex()]
+ if !ok {
+ return errors.New("chat session not found")
+ }
+
+ if len(parsedMessage.DeviceID) <= 0 {
+ return errors.New("'device' cannot be empty")
+ }
+
+ // register chat session
+ err := s.RegisterDeviceSubscription(&DeviceSubscription{
+ DeviceID: parsedMessage.DeviceID,
+ ChatSessionKeyHash: chatSession.SessionKeyHash,
+ PubKey: msg.Src,
+ })
+ if err != nil {
+ return err
+ }
+
+ // confirm that client has been successfully subscribed
+ msgParams := whisper.MessageParams{
+ Dst: msg.Src,
+ KeySym: chatSession.SessionKey,
+ Topic: MakeTopic([]byte(topicAckDeviceRegistration)),
+ Payload: []byte(`{"server": "0x` + s.nodeID + `"}`),
+ TTL: uint32(s.config.TTL),
+ PoW: s.config.MinimumPoW,
+ WorkTime: 5,
+ }
+ response, err := whisper.NewSentMessage(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to create server response message: %v", err)
+ }
+ env, err := response.Wrap(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to wrap server response message: %v", err)
+ }
+
+ if err := s.whisper.Send(env); err != nil {
+ return fmt.Errorf("failed to send server response message: %v", err)
+ }
+
+ log.Info("server confirms device registration", "dst",
+ common.ToHex(crypto.FromECDSAPub(msgParams.Dst)), "topic", msgParams.Topic.String())
+ return nil
+}
+
+// processSendNotificationRequest processes incoming client requests of type:
+// when client has session key, and ready to use it to send notifications
+func (s *NotificationServer) processSendNotificationRequest(msg *whisper.ReceivedMessage) error {
+ s.deviceSubscriptionsMu.RLock()
+ defer s.deviceSubscriptionsMu.RUnlock()
+
+ for _, subscriber := range s.deviceSubscriptions {
+ if subscriber.ChatSessionKeyHash == msg.SymKeyHash {
+ if whisper.IsPubKeyEqual(msg.Src, subscriber.PubKey) {
+ continue // no need to notify ourselves
+ }
+
+ if s.firebaseProvider != nil {
+ err := s.firebaseProvider.Send(subscriber.DeviceID, string(msg.Payload))
+ if err != nil {
+ log.Info("cannot send notification", "error", err)
+ }
+ }
+ }
+ }
+
+ return nil
+}
+
+// processClientSessionStatusRequest processes incoming client requests when:
+// client wants to learn whether it is already registered on some of the servers
+func (s *NotificationServer) processClientSessionStatusRequest(msg *whisper.ReceivedMessage) error {
+ s.clientSessionsMu.RLock()
+ defer s.clientSessionsMu.RUnlock()
+
+ if msg.Src == nil {
+ return errors.New("message 'from' field is required")
+ }
+
+ var sessionKey []byte
+ pubKey := hex.EncodeToString(crypto.FromECDSAPub(msg.Src))
+ for _, clientSession := range s.clientSessions {
+ if clientSession.ClientKey == pubKey {
+ sessionKey = clientSession.SessionKeyInput
+ break
+ }
+ }
+
+ // session is not found
+ if sessionKey == nil {
+ return nil
+ }
+
+ // let client know that we have session for a given public key
+ msgParams := whisper.MessageParams{
+ Src: s.protocolKey,
+ Dst: msg.Src,
+ Topic: MakeTopic([]byte(topicConfirmClientSession)),
+ Payload: []byte(`{"server": "0x` + s.nodeID + `", "key": "0x` + hex.EncodeToString(sessionKey) + `"}`),
+ TTL: uint32(s.config.TTL),
+ PoW: s.config.MinimumPoW,
+ WorkTime: 5,
+ }
+ response, err := whisper.NewSentMessage(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to create server response message: %v", err)
+ }
+ env, err := response.Wrap(&msgParams)
+ if err != nil {
+ return fmt.Errorf("failed to wrap server response message: %v", err)
+ }
+
+ if err := s.whisper.Send(env); err != nil {
+ return fmt.Errorf("failed to send server response message: %v", err)
+ }
+
+ log.Info("server confirms client session", "dst",
+ common.ToHex(crypto.FromECDSAPub(msgParams.Dst)), "topic", msgParams.Topic.String())
+ return nil
+}
+
+// processDropClientSessionRequest processes incoming client requests when:
+// client wants to drop its sessions with notification servers (if they exist)
+func (s *NotificationServer) processDropClientSessionRequest(msg *whisper.ReceivedMessage) error {
+ if msg.Src == nil {
+ return errors.New("message 'from' field is required")
+ }
+
+ s.clientSessionsMu.RLock()
+ pubKey := hex.EncodeToString(crypto.FromECDSAPub(msg.Src))
+ for _, clientSession := range s.clientSessions {
+ if clientSession.ClientKey == pubKey {
+ s.clientSessionsMu.RUnlock()
+ s.DropClientSession(clientSession.SessionKeyHash.Hex())
+ break
+ }
+ }
+ return nil
+}
+
+// installTopicFilter installs Whisper filter using symmetric key
+func (s *NotificationServer) installTopicFilter(topicName string, topicKey []byte) (filterID string, err error) {
+ topic := MakeTopicAsBytes([]byte(topicName))
+ filter := whisper.Filter{
+ KeySym: topicKey,
+ Topics: [][]byte{topic},
+ AllowP2P: true,
+ }
+ filterID, err = s.whisper.Subscribe(&filter)
+ if err != nil {
+ return "", fmt.Errorf("failed installing filter: %v", err)
+ }
+
+ log.Debug(fmt.Sprintf("installed topic filter %v for topic %x (%s)", filterID, topic, topicName))
+ return
+}
+
+// installKeyFilter installs Whisper filter using asymmetric key
+func (s *NotificationServer) installKeyFilter(topicName string, key *ecdsa.PrivateKey) (filterID string, err error) {
+ topic := MakeTopicAsBytes([]byte(topicName))
+ filter := whisper.Filter{
+ KeyAsym: key,
+ Topics: [][]byte{topic},
+ AllowP2P: true,
+ }
+ filterID, err = s.whisper.Subscribe(&filter)
+ if err != nil {
+ return "", fmt.Errorf("failed installing filter: %v", err)
+ }
+
+ log.Info(fmt.Sprintf("installed key filter %v for topic %x (%s)", filterID, topic, topicName))
+ return
+}
+
+// requestProcessorLoop processes incoming client requests, by listening to a given filter,
+// and executing process function on each incoming message
+func (s *NotificationServer) requestProcessorLoop(filterID string, topicWatched string, fn messageProcessingFn) {
+ log.Debug(fmt.Sprintf("request processor started: %s", topicWatched))
+
+ filter := s.whisper.GetFilter(filterID)
+ if filter == nil {
+ log.Warn(fmt.Sprintf("filter is not installed: %s (for topic '%s')", filterID, topicWatched))
+ return
+ }
+
+ ticker := time.NewTicker(time.Millisecond * 50)
+
+ for {
+ select {
+ case <-ticker.C:
+ messages := filter.Retrieve()
+ for _, msg := range messages {
+ if err := fn(msg); err != nil {
+ log.Warn("failed processing incoming request", "error", err)
+ }
+ }
+ case <-s.quit:
+ log.Debug("request processor stopped", "topic", topicWatched)
+ return
+ }
+ }
+}
+
+// makeSessionKey generates and saves random SymKey, allowing to establish secure
+// channel between server and client
+func (s *NotificationServer) makeSessionKey(keyName string) (sessionKey, sessionKeyDerived []byte, err error) {
+ // wipe out previous occurrence of symmetric key
+ s.whisper.DeleteSymKey(keyName)
+
+ sessionKey, err = makeSessionKey()
+ if err != nil {
+ return nil, nil, err
+ }
+
+ keyName, err = s.whisper.AddSymKey(keyName, sessionKey)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ sessionKeyDerived, err = s.whisper.GetSymKey(keyName)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ return
+}
diff --git a/whisper/notifications/utils.go b/whisper/notifications/utils.go
new file mode 100644
index 000000000..106752186
--- /dev/null
+++ b/whisper/notifications/utils.go
@@ -0,0 +1,84 @@
+package notifications
+
+import (
+ "crypto/sha512"
+ "errors"
+ "crypto/sha256"
+
+ crand "crypto/rand"
+ whisper "github.com/ethereum/go-ethereum/whisper/whisperv5"
+ "golang.org/x/crypto/pbkdf2"
+)
+
+// makeSessionKey returns pseudo-random symmetric key, which is used as
+// session key between notification client and server
+func makeSessionKey() ([]byte, error) {
+ // generate random key
+ const keyLen = 32
+ buf := make([]byte, keyLen)
+ _, err := crand.Read(buf)
+ if err != nil {
+ return nil, err
+ } else if !validateSymmetricKey(buf) {
+ return nil, errors.New("error in GenerateSymKey: crypto/rand failed to generate random data")
+ }
+
+ key := buf[:keyLen]
+ derived, err := deriveKeyMaterial(key, whisper.EnvelopeVersion)
+ if err != nil {
+ return nil, err
+ } else if !validateSymmetricKey(derived) {
+ return nil, errors.New("failed to derive valid key")
+ }
+
+ return derived, nil
+}
+
+// validateSymmetricKey returns false if the key contains all zeros
+func validateSymmetricKey(k []byte) bool {
+ return len(k) > 0 && !containsOnlyZeros(k)
+}
+
+// containsOnlyZeros checks if data is empty or not
+func containsOnlyZeros(data []byte) bool {
+ for _, b := range data {
+ if b != 0 {
+ return false
+ }
+ }
+ return true
+}
+
+// deriveKeyMaterial derives symmetric key material from the key or password./~~~
+// pbkdf2 is used for security, in case people use password instead of randomly generated keys.
+func deriveKeyMaterial(key []byte, version uint64) (derivedKey []byte, err error) {
+ if version == 0 {
+ // kdf should run no less than 0.1 seconds on average compute,
+ // because it's a once in a session experience
+ derivedKey := pbkdf2.Key(key, nil, 65356, 32, sha256.New)
+ return derivedKey, nil
+ } else {
+ return nil, errors.New("unknown version")
+ }
+}
+
+// MakeTopic returns Whisper topic *as bytes array* by generating cryptographic key from the provided password
+func MakeTopicAsBytes(password []byte) ([]byte) {
+ topic := make([]byte, int(whisper.TopicLength))
+ x := pbkdf2.Key(password, password, 8196, 128, sha512.New)
+ for i := 0; i < len(x); i++ {
+ topic[i%whisper.TopicLength] ^= x[i]
+ }
+
+ return topic
+}
+
+// MakeTopic returns Whisper topic by generating cryptographic key from the provided password
+func MakeTopic(password []byte) (topic whisper.TopicType) {
+ x := pbkdf2.Key(password, password, 8196, 128, sha512.New)
+ for i := 0; i < len(x); i++ {
+ topic[i%whisper.TopicLength] ^= x[i]
+ }
+
+ return
+}
diff --git a/whisper/whisperv2/whisper.go b/whisper/whisperv2/whisper.go
index 61c36918d..908346999 100644
--- a/whisper/whisperv2/whisper.go
+++ b/whisper/whisperv2/whisper.go
@@ -134,6 +134,13 @@ func (self *Whisper) NewIdentity() *ecdsa.PrivateKey {
return key
}
+// AddIdentity adds identity into the known identities list (for message decryption).
+func (self *Whisper) AddIdentity(key *ecdsa.PrivateKey) {
+ self.keysMu.Lock()
+ self.keys[string(crypto.FromECDSAPub(&key.PublicKey))] = key
+ self.keysMu.Unlock()
+}
+
// HasIdentity checks if the the whisper node is configured with the private key
// of the specified public pair.
func (self *Whisper) HasIdentity(key *ecdsa.PublicKey) bool {
diff --git a/whisper/whisperv5/api.go b/whisper/whisperv5/api.go
index 96c4b0e6c..e3c2f4a97 100644
--- a/whisper/whisperv5/api.go
+++ b/whisper/whisperv5/api.go
@@ -313,6 +313,16 @@ func (api *PublicWhisperAPI) Post(ctx context.Context, req NewMessage) (bool, er
return true, api.w.Send(env)
}
+// UninstallFilter is alias for Unsubscribe
+func (api *PublicWhisperAPI) UninstallFilter(id string) {
+ api.w.Unsubscribe(id)
+}
+
+// Unsubscribe disables and removes an existing filter.
+func (api *PublicWhisperAPI) Unsubscribe(id string) {
+ api.w.Unsubscribe(id)
+}
+
//go:generate gencodec -type Criteria -field-override criteriaOverride -out gen_criteria_json.go
// Criteria holds various filter options for inbound messages.
diff --git a/whisper/whisperv5/doc.go b/whisper/whisperv5/doc.go
index 7a57488bd..a6c9e610d 100644
--- a/whisper/whisperv5/doc.go
+++ b/whisper/whisperv5/doc.go
@@ -32,6 +32,8 @@ package whisperv5
import (
"fmt"
"time"
+
+ "github.com/ethereum/go-ethereum/p2p"
)
const (
@@ -85,3 +87,15 @@ type MailServer interface {
Archive(env *Envelope)
DeliverMail(whisperPeer *Peer, request *Envelope)
}
+
+// NotificationServer represents a notification server,
+// capable of screening incoming envelopes for special
+// topics, and once located, subscribe client nodes as
+// recipients to notifications (push notifications atm)
+type NotificationServer interface {
+ // Start initializes notification sending loop
+ Start(server *p2p.Server) error
+
+ // Stop stops notification sending loop, releasing related resources
+ Stop() error
+}
diff --git a/whisper/whisperv5/whisper.go b/whisper/whisperv5/whisper.go
index 85849ccce..c39e8b3e0 100644
--- a/whisper/whisperv5/whisper.go
+++ b/whisper/whisperv5/whisper.go
@@ -77,7 +77,8 @@ type Whisper struct {
statsMu sync.Mutex // guard stats
stats Statistics // Statistics of whisper node
- mailServer MailServer // MailServer interface
+ mailServer MailServer // MailServer interface
+ notificationServer NotificationServer
}
// New creates a Whisper client ready to communicate through the Ethereum P2P network.
@@ -156,6 +157,11 @@ func (w *Whisper) RegisterServer(server MailServer) {
w.mailServer = server
}
+// RegisterNotificationServer registers notification server with Whisper
+func (w *Whisper) RegisterNotificationServer(server NotificationServer) {
+ w.notificationServer = server