-
Notifications
You must be signed in to change notification settings - Fork 244
/
waku.go
1646 lines (1374 loc) · 45.6 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 wakuv2
import (
"context"
"crypto/ecdsa"
"crypto/sha256"
"database/sql"
"errors"
"fmt"
"math"
"math/rand"
"net"
"runtime"
"strings"
"sync"
"time"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p/p2p/host/autorelay"
"github.com/libp2p/go-libp2p/p2p/protocol/circuitv2/proto"
"github.com/libp2p/go-libp2p/p2p/protocol/identify"
"github.com/multiformats/go-multiaddr"
"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/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/p2p"
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/rpc"
"github.com/libp2p/go-libp2p"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/metrics"
"github.com/waku-org/go-waku/waku/v2/dnsdisc"
"github.com/waku-org/go-waku/waku/v2/protocol"
"github.com/waku-org/go-waku/waku/v2/protocol/filter"
"github.com/waku-org/go-waku/waku/v2/protocol/peer_exchange"
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
"github.com/waku-org/go-waku/waku/v2/utils"
"github.com/status-im/status-go/connection"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/signal"
"github.com/status-im/status-go/timesource"
"github.com/status-im/status-go/wakuv2/common"
"github.com/status-im/status-go/wakuv2/persistence"
node "github.com/waku-org/go-waku/waku/v2/node"
"github.com/waku-org/go-waku/waku/v2/protocol/pb"
"github.com/waku-org/go-waku/waku/v2/protocol/store"
storepb "github.com/waku-org/go-waku/waku/v2/protocol/store/pb"
)
const messageQueueLimit = 1024
const requestTimeout = 30 * time.Second
const autoRelayMinInterval = 2 * time.Second
const bootnodesQueryBackoffMs = 200
const bootnodesMaxRetries = 7
type settings struct {
LightClient bool // Indicates if the node is a light client
MinPeersForRelay int // Indicates the minimum number of peers required for using Relay Protocol
MaxMsgSize uint32 // Maximal message length allowed by the waku node
EnableConfirmations bool // Enable sending message confirmations
PeerExchange bool // Enable peer exchange
DiscoveryLimit int // Indicates the number of nodes to discover
Nameserver string // Optional nameserver to use for dns discovery
EnableDiscV5 bool // Indicates whether discv5 is enabled or not
}
// Waku represents a dark communication interface through the Ethereum
// network, using its very own P2P communication layer.
type Waku struct {
node *node.WakuNode // reference to a libp2p waku node
identifyService identify.IDService
appDB *sql.DB
dnsAddressCache map[string][]dnsdisc.DiscoveredNode // Map to store the multiaddresses returned by dns discovery
dnsAddressCacheLock *sync.RWMutex // lock to handle access to the map
filters *common.Filters // Message filters installed with Subscribe function
filterMsgChannel chan *protocol.Envelope // Channel for wakuv2 filter messages
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.ReceivedMessage // 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
bandwidthCounter *metrics.BandwidthCounter
sendQueue chan *protocol.Envelope
msgQueue chan *common.ReceivedMessage // Message queue for waku messages that havent been decoded
quit chan struct{} // Channel used for graceful exit
wg sync.WaitGroup
settings settings // Holds configuration settings that can be dynamically changed
settingsMu sync.RWMutex // Mutex to sync the settings access
envelopeFeed event.Feed
storeMsgIDs map[gethcommon.Hash]bool // Map of the currently processing ids
storeMsgIDsMu sync.RWMutex
connStatusSubscriptions map[string]*types.ConnStatusSubscription
connStatusMu sync.Mutex
timeSource func() time.Time // source of time for waku
logger *zap.Logger
// NTP Synced timesource
timesource *timesource.NTPTimeSource
// seededBootnodesForDiscV5 indicates whether we manage to retrieve discovery
// bootnodes successfully
seededBootnodesForDiscV5 bool
// offline indicates whether we have detected connectivity
offline bool
// connectionChanged is channel that notifies when connectivity has changed
connectionChanged chan struct{}
// discV5BootstrapNodes is the ENR to be used to fetch bootstrap nodes for discovery
discV5BootstrapNodes []string
}
func getUsableUDPPort() (int, error) {
conn, err := net.ListenUDP("udp", &net.UDPAddr{
IP: net.IPv4zero,
Port: 0,
})
if err != nil {
return 0, err
}
defer conn.Close()
return conn.LocalAddr().(*net.UDPAddr).Port, nil
}
// New creates a WakuV2 client ready to communicate through the LibP2P network.
func New(nodeKey string, fleet string, cfg *Config, logger *zap.Logger, appDB *sql.DB, timesource *timesource.NTPTimeSource) (*Waku, error) {
var err error
if logger == nil {
logger, err = zap.NewDevelopment()
if err != nil {
return nil, err
}
}
cfg = setDefaults(cfg)
if cfg.UDPPort == 0 {
cfg.UDPPort, err = getUsableUDPPort()
if err != nil {
return nil, err
}
}
logger.Debug("starting wakuv2 with config", zap.Any("config", cfg))
waku := &Waku{
appDB: appDB,
privateKeys: make(map[string]*ecdsa.PrivateKey),
symKeys: make(map[string][]byte),
envelopes: make(map[gethcommon.Hash]*common.ReceivedMessage),
expirations: make(map[uint32]mapset.Set),
msgQueue: make(chan *common.ReceivedMessage, messageQueueLimit),
sendQueue: make(chan *protocol.Envelope, 1000),
connStatusSubscriptions: make(map[string]*types.ConnStatusSubscription),
quit: make(chan struct{}),
connectionChanged: make(chan struct{}),
wg: sync.WaitGroup{},
dnsAddressCache: make(map[string][]dnsdisc.DiscoveredNode),
dnsAddressCacheLock: &sync.RWMutex{},
storeMsgIDs: make(map[gethcommon.Hash]bool),
storeMsgIDsMu: sync.RWMutex{},
timeSource: time.Now,
logger: logger,
discV5BootstrapNodes: cfg.DiscV5BootstrapNodes,
}
// Disabling light client mode if using status.prod or undefined
if fleet == "status.prod" || fleet == "" {
cfg.LightClient = false
}
waku.settings = settings{
MaxMsgSize: cfg.MaxMessageSize,
LightClient: cfg.LightClient,
MinPeersForRelay: cfg.MinPeersForRelay,
PeerExchange: cfg.PeerExchange,
DiscoveryLimit: cfg.DiscoveryLimit,
Nameserver: cfg.Nameserver,
EnableDiscV5: cfg.EnableDiscV5,
}
waku.filters = common.NewFilters()
waku.bandwidthCounter = metrics.NewBandwidthCounter()
waku.filterMsgChannel = make(chan *protocol.Envelope, 1024)
var privateKey *ecdsa.PrivateKey
if nodeKey != "" {
privateKey, err = crypto.HexToECDSA(nodeKey)
} else {
// If no nodekey is provided, create an ephemeral key
privateKey, err = crypto.GenerateKey()
}
if err != nil {
return nil, fmt.Errorf("failed to setup the go-waku private key: %v", err)
}
hostAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprint(cfg.Host, ":", cfg.Port))
if err != nil {
return nil, fmt.Errorf("failed to setup the network interface: %v", err)
}
ctx := context.Background()
connStatusChan := make(chan node.ConnStatus, 100)
if cfg.KeepAliveInterval == 0 {
cfg.KeepAliveInterval = DefaultConfig.KeepAliveInterval
}
libp2pOpts := node.DefaultLibP2POptions
libp2pOpts = append(libp2pOpts, libp2p.BandwidthReporter(waku.bandwidthCounter))
libp2pOpts = append(libp2pOpts, libp2p.NATPortMap())
libp2pOpts = append(libp2pOpts, libp2p.EnableHolePunching())
libp2pOpts = append(libp2pOpts, libp2p.EnableAutoRelayWithPeerSource(
waku.autoRelayPeerSource,
autorelay.WithMinInterval(autoRelayMinInterval),
))
opts := []node.WakuNodeOption{
node.WithLibP2POptions(libp2pOpts...),
node.WithPrivateKey(privateKey),
node.WithHostAddress(hostAddr),
node.WithConnectionStatusChannel(connStatusChan),
node.WithKeepAlive(time.Duration(cfg.KeepAliveInterval) * time.Second),
node.WithDiscoverParams(cfg.DiscoveryLimit),
node.WithLogger(logger),
}
if cfg.EnableDiscV5 {
bootnodes, err := waku.getDiscV5BootstrapNodes(ctx, cfg.DiscV5BootstrapNodes)
if err != nil {
logger.Error("failed to get bootstrap nodes", zap.Error(err))
return nil, err
}
opts = append(opts, node.WithDiscoveryV5(uint(cfg.UDPPort), bootnodes, cfg.AutoUpdate))
// Peer exchange requires DiscV5 to run (might change in future versions of the protocol)
if cfg.PeerExchange {
opts = append(opts, node.WithPeerExchange())
}
}
if cfg.LightClient {
opts = append(opts, node.WithWakuFilter(false))
} else {
relayOpts := []pubsub.Option{
pubsub.WithMaxMessageSize(int(waku.settings.MaxMsgSize)),
}
opts = append(opts, node.WithWakuRelayAndMinPeers(waku.settings.MinPeersForRelay, relayOpts...))
}
if cfg.EnableStore {
opts = append(opts, node.WithWakuStore())
dbStore, err := persistence.NewDBStore(logger, persistence.WithDB(appDB), persistence.WithRetentionPolicy(cfg.StoreCapacity, time.Duration(cfg.StoreSeconds)*time.Second))
if err != nil {
return nil, err
}
opts = append(opts, node.WithMessageProvider(dbStore))
}
if waku.node, err = node.New(opts...); err != nil {
return nil, fmt.Errorf("failed to create a go-waku node: %v", err)
}
idService, err := identify.NewIDService(waku.node.Host())
if err != nil {
return nil, err
}
waku.identifyService = idService
if err = waku.node.Start(ctx); err != nil {
return nil, fmt.Errorf("failed to start go-waku node: %v", err)
}
if err = waku.addWakuV2Peers(ctx, cfg); err != nil {
return nil, fmt.Errorf("failed to add wakuv2 peers: %v", err)
}
if cfg.EnableDiscV5 {
err := waku.node.DiscV5().Start(ctx)
if err != nil {
return nil, err
}
}
waku.wg.Add(4)
go func() {
defer waku.wg.Done()
isConnected := false
for {
select {
case <-waku.quit:
return
case c := <-connStatusChan:
waku.connStatusMu.Lock()
latestConnStatus := formatConnStatus(waku.node, c)
for k, subs := range waku.connStatusSubscriptions {
if subs.Active() {
subs.C <- latestConnStatus
} else {
delete(waku.connStatusSubscriptions, k)
}
}
waku.connStatusMu.Unlock()
signal.SendPeerStats(latestConnStatus)
if cfg.EnableDiscV5 {
// Restarting DiscV5
if !latestConnStatus.IsOnline && isConnected {
waku.logger.Debug("Restarting DiscV5: offline and is connected")
isConnected = false
waku.node.DiscV5().Stop()
} else if latestConnStatus.IsOnline && !isConnected {
waku.logger.Debug("Restarting DiscV5: online and is not connected")
isConnected = true
if !waku.node.DiscV5().IsStarted() {
err := waku.node.DiscV5().Start(ctx)
if err != nil {
waku.logger.Error("Could not start DiscV5", zap.Error(err))
}
}
}
}
}
}
}()
go waku.telemetryBandwidthStats(cfg.TelemetryServerURL)
go waku.runFilterMsgLoop()
go waku.runRelayMsgLoop()
go waku.runPeerExchangeLoop()
waku.logger.Info("setup the go-waku node successfully")
return waku, nil
}
func (w *Waku) SubscribeToConnStatusChanges() *types.ConnStatusSubscription {
w.connStatusMu.Lock()
defer w.connStatusMu.Unlock()
subscription := types.NewConnStatusSubscription()
w.connStatusSubscriptions[subscription.ID] = subscription
return subscription
}
func (w *Waku) getDiscV5BootstrapNodes(ctx context.Context, addresses []string) ([]*enode.Node, error) {
wg := sync.WaitGroup{}
mu := sync.Mutex{}
var result []*enode.Node
retrieveENR := func(d dnsdisc.DiscoveredNode, wg *sync.WaitGroup) {
mu.Lock()
defer mu.Unlock()
defer wg.Done()
if d.ENR != nil {
result = append(result, d.ENR)
}
}
for _, addrString := range addresses {
if addrString == "" {
continue
}
if strings.HasPrefix(addrString, "enrtree://") {
// Use DNS Discovery
wg.Add(1)
go func(addr string) {
defer wg.Done()
w.dnsDiscover(ctx, addr, retrieveENR)
}(addrString)
} else {
// It's a normal enr
bootnode, err := enode.Parse(enode.ValidSchemes, addrString)
if err != nil {
return nil, err
}
result = append(result, bootnode)
}
}
wg.Wait()
w.seededBootnodesForDiscV5 = len(result) > 0
return result, nil
}
type fnApplyToEachPeer func(d dnsdisc.DiscoveredNode, wg *sync.WaitGroup)
func (w *Waku) dnsDiscover(ctx context.Context, enrtreeAddress string, apply fnApplyToEachPeer) {
w.logger.Info("retrieving nodes", zap.String("enr", enrtreeAddress))
ctx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
w.dnsAddressCacheLock.Lock()
defer w.dnsAddressCacheLock.Unlock()
discNodes, ok := w.dnsAddressCache[enrtreeAddress]
if !ok {
w.settingsMu.RLock()
nameserver := w.settings.Nameserver
w.settingsMu.RUnlock()
var opts []dnsdisc.DnsDiscoveryOption
if nameserver != "" {
opts = append(opts, dnsdisc.WithNameserver(nameserver))
}
discoveredNodes, err := dnsdisc.RetrieveNodes(ctx, enrtreeAddress, opts...)
if err != nil {
w.logger.Warn("dns discovery error ", zap.Error(err))
return
}
if len(discoveredNodes) != 0 {
w.dnsAddressCache[enrtreeAddress] = append(w.dnsAddressCache[enrtreeAddress], discoveredNodes...)
discNodes = w.dnsAddressCache[enrtreeAddress]
}
}
wg := &sync.WaitGroup{}
wg.Add(len(discNodes))
for _, d := range discNodes {
apply(d, wg)
}
wg.Wait()
}
func (w *Waku) addWakuV2Peers(ctx context.Context, cfg *Config) error {
fnApply := func(d dnsdisc.DiscoveredNode, wg *sync.WaitGroup) {
if len(d.Addresses) != 0 {
go func(ma multiaddr.Multiaddr) {
w.identifyAndConnect(ctx, w.settings.LightClient, ma)
wg.Done()
}(d.Addresses[0])
}
}
identifyWg := &sync.WaitGroup{}
identifyWg.Add(len(cfg.WakuNodes))
for _, addrString := range cfg.WakuNodes {
addrString := addrString
if strings.HasPrefix(addrString, "enrtree://") {
// Use DNS Discovery
go func() {
w.dnsDiscover(ctx, addrString, fnApply)
identifyWg.Done()
}()
} else {
// It is a normal multiaddress
addr, err := multiaddr.NewMultiaddr(addrString)
if err != nil {
w.logger.Warn("invalid peer multiaddress", zap.String("ma", addrString), zap.Error(err))
continue
}
go func(ma multiaddr.Multiaddr) {
w.identifyAndConnect(ctx, cfg.LightClient, ma)
identifyWg.Done()
}(addr)
}
}
identifyWg.Wait()
return nil
}
func (w *Waku) identifyAndConnect(ctx context.Context, isLightClient bool, ma multiaddr.Multiaddr) {
peerInfo, err := peer.AddrInfoFromP2pAddr(ma)
if err != nil {
w.logger.Warn("invalid peer multiaddress", zap.String("addr", ma.String()), zap.Error(err))
return
}
ctx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
err = w.node.Host().Connect(ctx, *peerInfo)
if err != nil {
w.logger.Error("could not extract peerinfo", zap.String("ma", ma.String()), zap.Error(err))
return
}
conns := w.node.Host().Network().ConnsToPeer(peerInfo.ID)
if len(conns) == 0 {
return // No connection
}
w.identifyService.IdentifyConn(conns[0])
if isLightClient {
err = w.node.Host().Network().ClosePeer(peerInfo.ID)
if err != nil {
w.logger.Error("could not close connections to peer", zap.Any("peer", peerInfo.ID), zap.Error(err))
}
return
}
supportedProtocols, err := w.node.Host().Peerstore().SupportsProtocols(peerInfo.ID, relay.WakuRelayID_v200)
if err != nil {
w.logger.Error("could not obtain protocols", zap.Any("peer", peerInfo.ID), zap.Error(err))
return
}
if len(supportedProtocols) == 0 {
err = w.node.Host().Network().ClosePeer(peerInfo.ID)
if err != nil {
w.logger.Error("could not close connections to peer", zap.Any("peer", peerInfo.ID), zap.Error(err))
}
}
}
func (w *Waku) telemetryBandwidthStats(telemetryServerURL string) {
if telemetryServerURL == "" {
return
}
telemetry := NewBandwidthTelemetryClient(w.logger, telemetryServerURL)
ticker := time.NewTicker(time.Second * 20)
defer ticker.Stop()
today := time.Now()
for {
select {
case <-w.quit:
return
case now := <-ticker.C:
// Reset totals when day changes
if now.Day() != today.Day() {
today = now
w.bandwidthCounter.Reset()
}
storeStats := w.bandwidthCounter.GetBandwidthForProtocol(store.StoreID_v20beta4)
relayStats := w.bandwidthCounter.GetBandwidthForProtocol(relay.WakuRelayID_v200)
go telemetry.PushProtocolStats(relayStats, storeStats)
}
}
}
func (w *Waku) GetStats() types.StatsSummary {
stats := w.bandwidthCounter.GetBandwidthTotals()
return types.StatsSummary{
UploadRate: uint64(stats.RateOut),
DownloadRate: uint64(stats.RateIn),
}
}
func (w *Waku) runPeerExchangeLoop() {
defer w.wg.Done()
if w.settings.PeerExchange && !w.settings.LightClient {
// Currently peer exchange is only used for full nodes
// TODO: should it be used for lightpush? or lightpush nodes
// are only going to be selected from a specific set of peers?
return
}
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-w.quit:
return
case <-ticker.C:
w.logger.Debug("Running peer exchange loop")
connectedPeers := w.node.Host().Network().Peers()
peersWithRelay := 0
for _, p := range connectedPeers {
supportedProtocols, err := w.node.Host().Peerstore().SupportsProtocols(p, relay.WakuRelayID_v200)
if err != nil {
continue
}
if len(supportedProtocols) != 0 {
peersWithRelay++
}
}
peersToDiscover := w.settings.DiscoveryLimit - peersWithRelay
if peersToDiscover <= 0 {
continue
}
// We select only the nodes discovered via DNS Discovery that support peer exchange
w.dnsAddressCacheLock.RLock()
var withThesePeers []peer.ID
for _, record := range w.dnsAddressCache {
for _, discoveredNode := range record {
if len(discoveredNode.Addresses) == 0 {
continue
}
// Obtaining peer ID
peerIDString, err := discoveredNode.Addresses[0].ValueForProtocol(multiaddr.P_P2P)
if err != nil {
w.logger.Warn("multiaddress does not contain peerID", zap.String("multiaddr", discoveredNode.Addresses[0].String()))
continue // No peer ID available somehow
}
peerID, err := peer.Decode(peerIDString)
if err != nil {
w.logger.Warn("couldnt decode peerID", zap.String("peerIDString", peerIDString))
continue // Couldnt decode the peerID for some reason?
}
supportsProtocol, _ := w.node.Host().Peerstore().SupportsProtocols(peerID, peer_exchange.PeerExchangeID_v20alpha1)
if len(supportsProtocol) != 0 {
withThesePeers = append(withThesePeers, peerID)
}
}
}
w.dnsAddressCacheLock.RUnlock()
if len(withThesePeers) == 0 {
continue // No peers with peer exchange have been discovered via DNS Discovery so far, skip this iteration
}
err := w.node.PeerExchange().Request(context.Background(), peersToDiscover, peer_exchange.WithAutomaticPeerSelection(withThesePeers...))
if err != nil {
w.logger.Error("couldnt request peers via peer exchange", zap.Error(err))
}
}
}
}
func (w *Waku) runRelayMsgLoop() {
defer w.wg.Done()
if w.settings.LightClient {
return
}
sub, err := w.node.Relay().Subscribe(context.Background())
if err != nil {
fmt.Println("Could not subscribe:", err)
return
}
for {
select {
case <-w.quit:
sub.Unsubscribe()
return
case env := <-sub.C:
envelopeErrors, err := w.OnNewEnvelopes(env, common.RelayedMessageType)
if err != nil {
w.logger.Error("onNewEnvelope error", zap.Error(err))
}
// TODO: should these be handled?
_ = envelopeErrors
_ = err
}
}
}
func (w *Waku) runFilterMsgLoop() {
defer w.wg.Done()
if !w.settings.LightClient {
return
}
for {
select {
case <-w.quit:
return
case env := <-w.filterMsgChannel:
envelopeErrors, err := w.OnNewEnvelopes(env, common.RelayedMessageType)
// TODO: should these be handled?
_ = envelopeErrors
_ = err
}
}
}
func (w *Waku) subscribeWakuFilterTopic(topics [][]byte) {
var contentTopics []string
for _, topic := range topics {
contentTopics = append(contentTopics, common.BytesToTopic(topic).ContentTopic())
}
var err error
contentFilter := filter.ContentFilter{
Topic: relay.DefaultWakuTopic,
ContentTopics: contentTopics,
}
var wakuFilter filter.Filter
_, wakuFilter, err = w.node.Filter().Subscribe(context.Background(), contentFilter)
if err != nil {
w.logger.Warn("could not add wakuv2 filter for topics", zap.Any("topics", topics))
return
}
w.filterMsgChannel = wakuFilter.Chan
}
// MaxMessageSize returns the maximum accepted message size.
func (w *Waku) MaxMessageSize() uint32 {
w.settingsMu.RLock()
defer w.settingsMu.RUnlock()
return w.settings.MaxMsgSize
}
// 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: Name,
Version: VersionStr,
Service: NewPublicWakuAPI(w),
Public: false,
},
}
}
// Protocols returns the waku sub-protocols ran by this particular client.
func (w *Waku) Protocols() []p2p.Protocol {
return []p2p.Protocol{}
}
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)
}
// 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()