-
Notifications
You must be signed in to change notification settings - Fork 244
/
waku.go
1582 lines (1367 loc) · 45.3 KB
/
waku.go
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
// Copyright 2019 The Waku Library Authors.
//
// The Waku library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Waku library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty off
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Waku library. If not, see <http://www.gnu.org/licenses/>.
//
// This software uses the go-ethereum library, which is licensed
// under the GNU Lesser General Public Library, version 3 or any later.
package waku
import (
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"errors"
"fmt"
"runtime"
"sync"
"time"
"github.com/ethereum/go-ethereum/common/hexutil"
"go.uber.org/zap"
mapset "github.com/deckarep/golang-set"
"golang.org/x/crypto/pbkdf2"
gethcommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/log"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/rlp"
"github.com/ethereum/go-ethereum/rpc"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/waku/common"
v0 "github.com/status-im/status-go/waku/v0"
v1 "github.com/status-im/status-go/waku/v1"
)
const messageQueueLimit = 1024
type Bridge interface {
Pipe() (<-chan *common.Envelope, chan<- *common.Envelope)
}
type settings struct {
MaxMsgSize uint32 // Maximal message length allowed by the waku node
EnableConfirmations bool // Enable sending message confirmations
MinPow float64 // Minimal PoW required by the waku node
MinPowTolerance float64 // Minimal PoW tolerated by the waku node for a limited time
BloomFilter []byte // Bloom filter for topics of interest for this node
BloomFilterTolerance []byte // Bloom filter tolerated by the waku node for a limited time
TopicInterest map[common.TopicType]bool // Topic interest for this node
TopicInterestTolerance map[common.TopicType]bool // Topic interest tolerated by the waku node for a limited time
SoftBlacklistedPeerIDs map[string]bool // SoftBlacklistedPeerIDs is a list of peer ids that we want to keep connected but silently drop any envelope from
BloomFilterMode bool // Whether we should match against bloom-filter only
LightClient bool // Light client mode enabled does not forward messages
RestrictLightClientsConn bool // Restrict connection between two light clients
SyncAllowance int // Maximum time in seconds allowed to process the waku-related messages
FullNode bool // Whether this is to be run in FullNode settings
}
// Waku represents a dark communication interface through the Ethereum
// network, using its very own P2P communication layer.
type Waku struct {
protocols []p2p.Protocol // Peer description and parameters
filters *common.Filters // Message filters installed with Subscribe function
privateKeys map[string]*ecdsa.PrivateKey // Private key storage
symKeys map[string][]byte // Symmetric key storage
keyMu sync.RWMutex // Mutex associated with key stores
envelopes map[gethcommon.Hash]*common.Envelope // Pool of envelopes currently tracked by this node
expirations map[uint32]mapset.Set // Message expiration pool
poolMu sync.RWMutex // Mutex to sync the message and expiration pools
stats *common.StatsTracker
peers map[common.Peer]struct{} // Set of currently active peers
peerMu sync.RWMutex // Mutex to sync the active peer set
msgQueue chan *common.Envelope // Message queue for normal waku messages
p2pMsgQueue chan interface{} // Message queue for peer-to-peer messages (not to be forwarded any further) and history delivery confirmations.
quit chan struct{} // Channel used for graceful exit
settings settings // Holds configuration settings that can be dynamically changed
settingsMu sync.RWMutex // Mutex to sync the settings access
mailServer MailServer
rateLimiter *common.PeerRateLimiter
envelopeFeed event.Feed
timeSource func() time.Time // source of time for waku
bridge Bridge
bridgeWg sync.WaitGroup
cancelBridge chan struct{}
logger *zap.Logger
}
// New creates a Waku client ready to communicate through the Ethereum P2P network.
func New(cfg *Config, logger *zap.Logger) *Waku {
if logger == nil {
logger = zap.NewNop()
}
logger.Debug("starting waku with config", zap.Any("config", cfg))
if cfg == nil {
c := DefaultConfig
cfg = &c
}
waku := &Waku{
privateKeys: make(map[string]*ecdsa.PrivateKey),
symKeys: make(map[string][]byte),
envelopes: make(map[gethcommon.Hash]*common.Envelope),
expirations: make(map[uint32]mapset.Set),
peers: make(map[common.Peer]struct{}),
msgQueue: make(chan *common.Envelope, messageQueueLimit),
p2pMsgQueue: make(chan interface{}, messageQueueLimit),
quit: make(chan struct{}),
timeSource: time.Now,
logger: logger,
}
waku.settings = settings{
MaxMsgSize: cfg.MaxMessageSize,
MinPow: cfg.MinimumAcceptedPoW,
MinPowTolerance: cfg.MinimumAcceptedPoW,
EnableConfirmations: cfg.EnableConfirmations,
LightClient: cfg.LightClient,
FullNode: cfg.FullNode,
BloomFilterMode: cfg.BloomFilterMode,
SoftBlacklistedPeerIDs: make(map[string]bool),
RestrictLightClientsConn: cfg.RestrictLightClientsConn,
SyncAllowance: common.DefaultSyncAllowance,
}
for _, peerID := range cfg.SoftBlacklistedPeerIDs {
waku.settings.SoftBlacklistedPeerIDs[peerID] = true
}
if cfg.FullNode {
waku.settings.BloomFilter = common.MakeFullNodeBloom()
waku.settings.BloomFilterTolerance = common.MakeFullNodeBloom()
}
waku.filters = common.NewFilters()
waku.stats = &common.StatsTracker{}
// p2p waku sub-protocol handler
waku.protocols = []p2p.Protocol{{
Name: v0.Name,
Version: uint(v0.Version),
Length: v0.NumberOfMessageCodes,
Run: waku.handlePeerV0,
NodeInfo: func() interface{} {
return map[string]interface{}{
"version": v0.VersionStr,
"maxMessageSize": waku.MaxMessageSize(),
"minimumPoW": waku.MinPow(),
}
},
},
{
Name: v1.Name,
Version: uint(v1.Version),
Length: v1.NumberOfMessageCodes,
Run: waku.handlePeerV1,
NodeInfo: func() interface{} {
return map[string]interface{}{
"version": v1.VersionStr,
"maxMessageSize": waku.MaxMessageSize(),
"minimumPoW": waku.MinPow(),
}
},
},
}
return waku
}
func (w *Waku) GetStats() types.StatsSummary {
return w.stats.GetStats()
}
// MinPow returns the PoW value required by this node.
func (w *Waku) MinPow() float64 {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.MinPow
}
// SetMinimumPoW sets the minimal PoW required by this node
func (w *Waku) SetMinimumPoW(val float64, tolerate bool) error {
if val < 0.0 {
return fmt.Errorf("invalid PoW: %f", val)
}
w.settingsMu.Lock()
w.settings.MinPow = val
w.settingsMu.Unlock()
w.notifyPeersAboutPowRequirementChange(val)
if tolerate {
go func() {
// allow some time before all the peers have processed the notification
select {
case <-w.quit:
return
case <-time.After(time.Duration(w.settings.SyncAllowance) * time.Second):
w.settingsMu.Lock()
w.settings.MinPowTolerance = val
w.settingsMu.Unlock()
}
}()
}
return nil
}
// MinPowTolerance returns the value of minimum PoW which is tolerated for a limited
// time after PoW was changed. If sufficient time have elapsed or no change of PoW
// have ever occurred, the return value will be the same as return value of MinPow().
func (w *Waku) MinPowTolerance() float64 {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.MinPowTolerance
}
// BloomFilter returns the aggregated bloom filter for all the topics of interest.
// The nodes are required to send only messages that match the advertised bloom filter.
// If a message does not match the bloom, it will tantamount to spam, and the peer will
// be disconnected.
func (w *Waku) BloomFilter() []byte {
if w.FullNode() {
return common.MakeFullNodeBloom()
}
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.BloomFilter
}
// BloomFilterTolerance returns the bloom filter which is tolerated for a limited
// time after new bloom was advertised to the peers. If sufficient time have elapsed
// or no change of bloom filter have ever occurred, the return value will be the same
// as return value of BloomFilter().
func (w *Waku) BloomFilterTolerance() []byte {
if w.FullNode() {
return common.MakeFullNodeBloom()
}
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.BloomFilterTolerance
}
// BloomFilterMode returns whether the node is running in bloom filter mode
func (w *Waku) BloomFilterMode() bool {
if w.FullNode() {
return true
}
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.BloomFilterMode
}
// SetBloomFilter sets the new bloom filter
func (w *Waku) SetBloomFilter(bloom []byte) error {
if len(bloom) != common.BloomFilterSize {
return fmt.Errorf("invalid bloom filter size: %d", len(bloom))
}
b := make([]byte, common.BloomFilterSize)
copy(b, bloom)
w.settingsMu.Lock()
w.settings.BloomFilter = b
// Setting bloom filter reset topic interest
w.settings.TopicInterest = nil
w.settingsMu.Unlock()
w.notifyPeersAboutBloomFilterChange(b)
go func() {
// allow some time before all the peers have processed the notification
select {
case <-w.quit:
return
case <-time.After(time.Duration(w.settings.SyncAllowance) * time.Second):
w.settingsMu.Lock()
w.settings.BloomFilterTolerance = b
w.settingsMu.Unlock()
}
}()
return nil
}
// TopicInterest returns the all the topics of interest.
// The nodes are required to send only messages that match the advertised topics.
// If a message does not match the topic-interest, it will tantamount to spam, and the peer will
// be disconnected.
func (w *Waku) TopicInterest() []common.TopicType {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
// Return nil if FullNode as otherwise topic interest will have precedence
if w.settings.FullNode || w.settings.TopicInterest == nil {
return nil
}
topicInterest := make([]common.TopicType, len(w.settings.TopicInterest))
i := 0
for topic := range w.settings.TopicInterest {
topicInterest[i] = topic
i++
}
return topicInterest
}
// updateTopicInterest adds a new topic interest
// and informs the peers
func (w *Waku) updateTopicInterest(f *common.Filter) error {
newTopicInterest := w.TopicInterest()
for _, t := range f.Topics {
top := common.BytesToTopic(t)
newTopicInterest = append(newTopicInterest, top)
}
return w.SetTopicInterest(newTopicInterest)
}
// SetTopicInterest sets the new topicInterest
func (w *Waku) SetTopicInterest(topicInterest []common.TopicType) error {
var topicInterestMap map[common.TopicType]bool
if len(topicInterest) > common.MaxTopicInterest {
return fmt.Errorf("invalid topic interest: %d", len(topicInterest))
}
if topicInterest != nil {
topicInterestMap = make(map[common.TopicType]bool, len(topicInterest))
for _, topic := range topicInterest {
topicInterestMap[topic] = true
}
}
w.settingsMu.Lock()
w.settings.TopicInterest = topicInterestMap
// Setting topic interest resets bloom filter
w.settings.BloomFilter = nil
w.settingsMu.Unlock()
w.notifyPeersAboutTopicInterestChange(topicInterest)
go func() {
// allow some time before all the peers have processed the notification
select {
case <-w.quit:
return
case <-time.After(time.Duration(w.settings.SyncAllowance) * time.Second):
w.settingsMu.Lock()
w.settings.TopicInterestTolerance = topicInterestMap
w.settingsMu.Unlock()
}
}()
return nil
}
// MaxMessageSize returns the maximum accepted message size.
func (w *Waku) MaxMessageSize() uint32 {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.MaxMsgSize
}
// SetMaxMessageSize sets the maximal message size allowed by this node
func (w *Waku) SetMaxMessageSize(size uint32) error {
if size > common.MaxMessageSize {
return fmt.Errorf("message size too large [%d>%d]", size, common.MaxMessageSize)
}
w.settingsMu.Lock()
w.settings.MaxMsgSize = size
w.settingsMu.Unlock()
return nil
}
// LightClientMode indicates is this node is light client (does not forward any messages)
func (w *Waku) LightClientMode() bool {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.LightClient
}
// SetLightClientMode makes node light client (does not forward any messages)
func (w *Waku) SetLightClientMode(v bool) {
w.settingsMu.Lock()
w.settings.LightClient = v
w.settingsMu.Unlock()
}
// LightClientModeConnectionRestricted indicates that connection to light client in light client mode not allowed
func (w *Waku) LightClientModeConnectionRestricted() bool {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.RestrictLightClientsConn
}
// PacketRateLimiting returns RateLimits information for packets
func (w *Waku) PacketRateLimits() common.RateLimits {
if w.rateLimiter == nil {
return common.RateLimits{}
}
return common.RateLimits{
IPLimits: uint64(w.rateLimiter.PacketLimitPerSecIP),
PeerIDLimits: uint64(w.rateLimiter.PacketLimitPerSecPeerID),
}
}
// BytesRateLimiting returns RateLimits information for bytes
func (w *Waku) BytesRateLimits() common.RateLimits {
if w.rateLimiter == nil {
return common.RateLimits{}
}
return common.RateLimits{
IPLimits: uint64(w.rateLimiter.BytesLimitPerSecIP),
PeerIDLimits: uint64(w.rateLimiter.BytesLimitPerSecPeerID),
}
}
// ConfirmationsEnabled returns true if message confirmations are enabled.
func (w *Waku) ConfirmationsEnabled() bool {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.EnableConfirmations
}
// CurrentTime returns current time.
func (w *Waku) CurrentTime() time.Time {
return w.timeSource()
}
// SetTimeSource assigns a particular source of time to a waku object.
func (w *Waku) SetTimeSource(timesource func() time.Time) {
w.timeSource = timesource
}
// APIs returns the RPC descriptors the Waku implementation offers
func (w *Waku) APIs() []rpc.API {
return []rpc.API{
{
Namespace: v0.Name,
Version: v0.VersionStr,
Service: NewPublicWakuAPI(w),
Public: false,
},
}
}
// Protocols returns the waku sub-protocols ran by this particular client.
func (w *Waku) Protocols() []p2p.Protocol {
return w.protocols
}
// RegisterMailServer registers MailServer interface.
// MailServer will process all the incoming messages with p2pRequestCode.
func (w *Waku) RegisterMailServer(server MailServer) {
w.mailServer = server
}
// SetRateLimiter registers a rate limiter.
func (w *Waku) RegisterRateLimiter(r *common.PeerRateLimiter) {
w.rateLimiter = r
}
// RegisterBridge registers a new Bridge that moves envelopes
// between different subprotocols.
// It's important that a bridge is registered before the service
// is started, otherwise, it won't read and propagate envelopes.
func (w *Waku) RegisterBridge(b Bridge) {
if w.cancelBridge != nil {
close(w.cancelBridge)
}
w.bridge = b
w.cancelBridge = make(chan struct{})
w.bridgeWg.Add(1)
go w.readBridgeLoop()
}
func (w *Waku) readBridgeLoop() {
defer w.bridgeWg.Done()
out, _ := w.bridge.Pipe()
for {
select {
case <-w.cancelBridge:
return
case env := <-out:
_, err := w.addAndBridge(env, false, true)
if err != nil {
common.BridgeReceivedFailed.Inc()
w.logger.Warn(
"failed to add a bridged envelope",
zap.Binary("ID", env.Hash().Bytes()),
zap.Error(err),
)
} else {
common.BridgeReceivedSucceed.Inc()
w.logger.Debug("bridged envelope successfully", zap.Binary("ID", env.Hash().Bytes()))
w.envelopeFeed.Send(common.EnvelopeEvent{
Event: common.EventEnvelopeReceived,
Topic: env.Topic,
Hash: env.Hash(),
})
}
}
}
}
func (w *Waku) SendEnvelopeEvent(event common.EnvelopeEvent) int {
return w.envelopeFeed.Send(event)
}
// SubscribeEnvelopeEvents subscribes to envelopes feed.
// In order to prevent blocking waku producers events must be amply buffered.
func (w *Waku) SubscribeEnvelopeEvents(events chan<- common.EnvelopeEvent) event.Subscription {
return w.envelopeFeed.Subscribe(events)
}
func (w *Waku) notifyPeersAboutPowRequirementChange(pow float64) {
arr := w.getPeers()
for _, p := range arr {
err := p.NotifyAboutPowRequirementChange(pow)
if err != nil {
// allow one retry
err = p.NotifyAboutPowRequirementChange(pow)
}
if err != nil {
w.logger.Warn("failed to notify peer about new pow requirement", zap.Binary("peer", p.ID()), zap.Error(err))
}
}
}
func (w *Waku) FullNode() bool {
w.settingsMu.RLock()
// If full node, nothing to do
fullNode := w.settings.FullNode
w.settingsMu.RUnlock()
return fullNode
}
func (w *Waku) notifyPeersAboutBloomFilterChange(bloom []byte) {
if w.FullNode() {
return
}
arr := w.getPeers()
for _, p := range arr {
err := p.NotifyAboutBloomFilterChange(bloom)
if err != nil {
// allow one retry
err = p.NotifyAboutBloomFilterChange(bloom)
}
if err != nil {
w.logger.Warn("failed to notify peer about new bloom filter change", zap.Binary("peer", p.ID()), zap.Error(err))
}
}
}
func (w *Waku) notifyPeersAboutTopicInterestChange(topicInterest []common.TopicType) {
if w.FullNode() {
return
}
arr := w.getPeers()
for _, p := range arr {
err := p.NotifyAboutTopicInterestChange(topicInterest)
if err != nil {
// allow one retry
err = p.NotifyAboutTopicInterestChange(topicInterest)
}
if err != nil {
w.logger.Warn("failed to notify peer about new topic interest", zap.Binary("peer", p.ID()), zap.Error(err))
}
}
}
func (w *Waku) getPeers() []common.Peer {
w.peerMu.Lock()
arr := make([]common.Peer, len(w.peers))
i := 0
for p := range w.peers {
arr[i] = p
i++
}
w.peerMu.Unlock()
return arr
}
// getPeer retrieves peer by ID
func (w *Waku) getPeer(peerID []byte) (common.Peer, error) {
w.peerMu.Lock()
defer w.peerMu.Unlock()
for p := range w.peers {
if bytes.Equal(peerID, p.ID()) {
return p, nil
}
}
return nil, fmt.Errorf("could not find peer with ID: %x", peerID)
}
// AllowP2PMessagesFromPeer marks specific peer trusted,
// which will allow it to send historic (expired) messages.
func (w *Waku) AllowP2PMessagesFromPeer(peerID []byte) error {
p, err := w.getPeer(peerID)
if err != nil {
return err
}
p.SetPeerTrusted(true)
return nil
}
// RequestHistoricMessages sends a message with p2pRequestCode to a specific peer,
// which is known to implement MailServer interface, and is supposed to process this
// request and respond with a number of peer-to-peer messages (possibly expired),
// which are not supposed to be forwarded any further.
// The waku protocol is agnostic of the format and contents of envelope.
func (w *Waku) RequestHistoricMessages(peerID []byte, envelope *common.Envelope) error {
return w.RequestHistoricMessagesWithTimeout(peerID, envelope, 0)
}
// RequestHistoricMessagesWithTimeout acts as RequestHistoricMessages but requires to pass a timeout.
// It sends an event EventMailServerRequestExpired after the timeout.
func (w *Waku) RequestHistoricMessagesWithTimeout(peerID []byte, envelope *common.Envelope, timeout time.Duration) error {
p, err := w.getPeer(peerID)
if err != nil {
return err
}
p.SetPeerTrusted(true)
w.envelopeFeed.Send(common.EnvelopeEvent{
Peer: p.EnodeID(),
Topic: envelope.Topic,
Hash: envelope.Hash(),
Event: common.EventMailServerRequestSent,
})
err = p.RequestHistoricMessages(envelope)
if timeout != 0 {
go w.expireRequestHistoricMessages(p.EnodeID(), envelope.Hash(), timeout)
}
return err
}
func (w *Waku) SendMessagesRequest(peerID []byte, request common.MessagesRequest) error {
if err := request.Validate(); err != nil {
return err
}
p, err := w.getPeer(peerID)
if err != nil {
return err
}
p.SetPeerTrusted(true)
if err := p.SendMessagesRequest(request); err != nil {
return err
}
w.envelopeFeed.Send(common.EnvelopeEvent{
Peer: p.EnodeID(),
Hash: gethcommon.BytesToHash(request.ID),
Event: common.EventMailServerRequestSent,
})
return nil
}
func (w *Waku) expireRequestHistoricMessages(peer enode.ID, hash gethcommon.Hash, timeout time.Duration) {
timer := time.NewTimer(timeout)
defer timer.Stop()
select {
case <-w.quit:
return
case <-timer.C:
w.envelopeFeed.Send(common.EnvelopeEvent{
Peer: peer,
Hash: hash,
Event: common.EventMailServerRequestExpired,
})
}
}
func (w *Waku) SendHistoricMessageResponse(peerID []byte, payload []byte) error {
peer, err := w.getPeer(peerID)
if err != nil {
return err
}
return peer.SendHistoricMessageResponse(payload)
}
// SendP2PMessage sends a peer-to-peer message to a specific peer.
// It sends one or more envelopes in a single batch.
func (w *Waku) SendP2PMessages(peerID []byte, envelopes ...*common.Envelope) error {
p, err := w.getPeer(peerID)
if err != nil {
return err
}
return p.SendP2PMessages(envelopes)
}
// SendRawP2PDirect sends a peer-to-peer message to a specific peer.
// It sends one or more envelopes in a single batch.
func (w *Waku) SendRawP2PDirect(peerID []byte, envelopes ...rlp.RawValue) error {
p, err := w.getPeer(peerID)
if err != nil {
return err
}
return p.SendRawP2PDirect(envelopes)
}
// NewKeyPair generates a new cryptographic identity for the client, and injects
// it into the known identities for message decryption. Returns ID of the new key pair.
func (w *Waku) NewKeyPair() (string, error) {
key, err := crypto.GenerateKey()
if err != nil || !validatePrivateKey(key) {
key, err = crypto.GenerateKey() // retry once
}
if err != nil {
return "", err
}
if !validatePrivateKey(key) {
return "", fmt.Errorf("failed to generate valid key")
}
id, err := toDeterministicID(hexutil.Encode(crypto.FromECDSAPub(&key.PublicKey)), common.KeyIDSize)
if err != nil {
return "", err
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.privateKeys[id] != nil {
return "", fmt.Errorf("failed to generate unique ID")
}
w.privateKeys[id] = key
return id, nil
}
// DeleteKeyPair deletes the specified key if it exists.
func (w *Waku) DeleteKeyPair(key string) bool {
deterministicID, err := toDeterministicID(key, common.KeyIDSize)
if err != nil {
return false
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.privateKeys[deterministicID] != nil {
delete(w.privateKeys, deterministicID)
return true
}
return false
}
// AddKeyPair imports a asymmetric private key and returns it identifier.
func (w *Waku) AddKeyPair(key *ecdsa.PrivateKey) (string, error) {
id, err := makeDeterministicID(hexutil.Encode(crypto.FromECDSAPub(&key.PublicKey)), common.KeyIDSize)
if err != nil {
return "", err
}
if w.HasKeyPair(id) {
return id, nil // no need to re-inject
}
w.keyMu.Lock()
w.privateKeys[id] = key
w.keyMu.Unlock()
return id, nil
}
// SelectKeyPair adds cryptographic identity, and makes sure
// that it is the only private key known to the node.
func (w *Waku) SelectKeyPair(key *ecdsa.PrivateKey) error {
id, err := makeDeterministicID(hexutil.Encode(crypto.FromECDSAPub(&key.PublicKey)), common.KeyIDSize)
if err != nil {
return err
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
w.privateKeys = make(map[string]*ecdsa.PrivateKey) // reset key store
w.privateKeys[id] = key
return nil
}
// DeleteKeyPairs removes all cryptographic identities known to the node
func (w *Waku) DeleteKeyPairs() error {
w.keyMu.Lock()
defer w.keyMu.Unlock()
w.privateKeys = make(map[string]*ecdsa.PrivateKey)
return nil
}
// HasKeyPair checks if the waku node is configured with the private key
// of the specified public pair.
func (w *Waku) HasKeyPair(id string) bool {
deterministicID, err := toDeterministicID(id, common.KeyIDSize)
if err != nil {
return false
}
w.keyMu.RLock()
defer w.keyMu.RUnlock()
return w.privateKeys[deterministicID] != nil
}
// GetPrivateKey retrieves the private key of the specified identity.
func (w *Waku) GetPrivateKey(id string) (*ecdsa.PrivateKey, error) {
deterministicID, err := toDeterministicID(id, common.KeyIDSize)
if err != nil {
return nil, err
}
w.keyMu.RLock()
defer w.keyMu.RUnlock()
key := w.privateKeys[deterministicID]
if key == nil {
return nil, fmt.Errorf("invalid id")
}
return key, nil
}
// GenerateSymKey generates a random symmetric key and stores it under id,
// which is then returned. Will be used in the future for session key exchange.
func (w *Waku) GenerateSymKey() (string, error) {
key, err := common.GenerateSecureRandomData(common.AESKeyLength)
if err != nil {
return "", err
} else if !common.ValidateDataIntegrity(key, common.AESKeyLength) {
return "", fmt.Errorf("error in GenerateSymKey: crypto/rand failed to generate random data")
}
id, err := common.GenerateRandomID()
if err != nil {
return "", fmt.Errorf("failed to generate ID: %s", err)
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.symKeys[id] != nil {
return "", fmt.Errorf("failed to generate unique ID")
}
w.symKeys[id] = key
return id, nil
}
// AddSymKey stores the key with a given id.
func (w *Waku) AddSymKey(id string, key []byte) (string, error) {
deterministicID, err := toDeterministicID(id, common.KeyIDSize)
if err != nil {
return "", err
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.symKeys[deterministicID] != nil {
return "", fmt.Errorf("key already exists: %v", id)
}
w.symKeys[deterministicID] = key
return deterministicID, nil
}
// AddSymKeyDirect stores the key, and returns its id.
func (w *Waku) AddSymKeyDirect(key []byte) (string, error) {
if len(key) != common.AESKeyLength {
return "", fmt.Errorf("wrong key size: %d", len(key))
}
id, err := common.GenerateRandomID()
if err != nil {
return "", fmt.Errorf("failed to generate ID: %s", err)
}
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.symKeys[id] != nil {
return "", fmt.Errorf("failed to generate unique ID")
}
w.symKeys[id] = key
return id, nil
}
// AddSymKeyFromPassword generates the key from password, stores it, and returns its id.
func (w *Waku) AddSymKeyFromPassword(password string) (string, error) {
id, err := common.GenerateRandomID()
if err != nil {
return "", fmt.Errorf("failed to generate ID: %s", err)
}
if w.HasSymKey(id) {
return "", fmt.Errorf("failed to generate unique ID")
}
// kdf should run no less than 0.1 seconds on an average computer,
// because it's an once in a session experience
derived := pbkdf2.Key([]byte(password), nil, 65356, common.AESKeyLength, sha256.New)
w.keyMu.Lock()
defer w.keyMu.Unlock()
// double check is necessary, because deriveKeyMaterial() is very slow
if w.symKeys[id] != nil {
return "", fmt.Errorf("critical error: failed to generate unique ID")
}
w.symKeys[id] = derived
return id, nil
}
// HasSymKey returns true if there is a key associated with the given id.
// Otherwise returns false.
func (w *Waku) HasSymKey(id string) bool {
w.keyMu.RLock()
defer w.keyMu.RUnlock()
return w.symKeys[id] != nil
}
// DeleteSymKey deletes the key associated with the name string if it exists.
func (w *Waku) DeleteSymKey(id string) bool {
w.keyMu.Lock()
defer w.keyMu.Unlock()
if w.symKeys[id] != nil {
delete(w.symKeys, id)
return true
}
return false
}
// GetSymKey returns the symmetric key associated with the given id.
func (w *Waku) GetSymKey(id string) ([]byte, error) {
w.keyMu.RLock()
defer w.keyMu.RUnlock()
if w.symKeys[id] != nil {
return w.symKeys[id], nil
}
return nil, fmt.Errorf("non-existent key ID")
}
// Subscribe installs a new message handler used for filtering, decrypting
// and subsequent storing of incoming messages.
func (w *Waku) Subscribe(f *common.Filter) (string, error) {
s, err := w.filters.Install(f)
if err != nil {
return s, err
}
err = w.updateSettingsForFilter(f)
if err != nil {
w.filters.Uninstall(s)
return s, err
}
return s, nil
}
func (w *Waku) updateSettingsForFilter(f *common.Filter) error {
w.settingsMu.RLock()
topicInterestMode := !w.settings.BloomFilterMode
w.settingsMu.RUnlock()
if topicInterestMode {
err := w.updateTopicInterest(f)
if err != nil {
return err
}
} else {
err := w.updateBloomFilter(f)
if err != nil {
return err
}
}