-
Notifications
You must be signed in to change notification settings - Fork 0
/
nwaku.go
3346 lines (2808 loc) · 92.7 KB
/
nwaku.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
//go:build use_nwaku
// +build use_nwaku
package wakuv2
/*
#cgo LDFLAGS: -L../third_party/nwaku/build/ -lnegentropy -lwaku
#cgo LDFLAGS: -L../third_party/nwaku -Wl,-rpath,../third_party/nwaku/build/
#include "../third_party/nwaku/library/libwaku.h"
#include <stdio.h>
#include <stdlib.h>
extern void globalEventCallback(int ret, char* msg, size_t len, void* userData);
typedef struct {
int ret;
char* msg;
size_t len;
} Resp;
static void* allocResp() {
return calloc(1, sizeof(Resp));
}
static void freeResp(void* resp) {
if (resp != NULL) {
free(resp);
}
}
static char* getMyCharPtr(void* resp) {
if (resp == NULL) {
return NULL;
}
Resp* m = (Resp*) resp;
return m->msg;
}
static size_t getMyCharLen(void* resp) {
if (resp == NULL) {
return 0;
}
Resp* m = (Resp*) resp;
return m->len;
}
static int getRet(void* resp) {
if (resp == NULL) {
return 0;
}
Resp* m = (Resp*) resp;
return m->ret;
}
// resp must be set != NULL in case interest on retrieving data from the callback
static void callback(int ret, char* msg, size_t len, void* resp) {
if (resp != NULL) {
Resp* m = (Resp*) resp;
m->ret = ret;
m->msg = msg;
m->len = len;
}
}
#define WAKU_CALL(call) \
do { \
int ret = call; \
if (ret != 0) { \
printf("Failed the call to: %s. Returned code: %d\n", #call, ret); \
exit(1); \
} \
} while (0)
static void* cGoWakuNew(const char* configJson, void* resp) {
// We pass NULL because we are not interested in retrieving data from this callback
void* ret = waku_new(configJson, (WakuCallBack) callback, resp);
return ret;
}
static void cGoWakuStart(void* wakuCtx, void* resp) {
WAKU_CALL(waku_start(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuStop(void* wakuCtx, void* resp) {
WAKU_CALL(waku_stop(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuDestroy(void* wakuCtx, void* resp) {
WAKU_CALL(waku_destroy(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuStartDiscV5(void* wakuCtx, void* resp) {
WAKU_CALL(waku_start_discv5(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuStopDiscV5(void* wakuCtx, void* resp) {
WAKU_CALL(waku_stop_discv5(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuVersion(void* wakuCtx, void* resp) {
WAKU_CALL(waku_version(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuSetEventCallback(void* wakuCtx) {
// The 'globalEventCallback' Go function is shared amongst all possible Waku instances.
// Given that the 'globalEventCallback' is shared, we pass again the
// wakuCtx instance but in this case is needed to pick up the correct method
// that will handle the event.
// In other words, for every call the libwaku makes to globalEventCallback,
// the 'userData' parameter will bring the context of the node that registered
// that globalEventCallback.
// This technique is needed because cgo only allows to export Go functions and not methods.
waku_set_event_callback(wakuCtx, (WakuCallBack) globalEventCallback, wakuCtx);
}
static void cGoWakuContentTopic(void* wakuCtx,
char* appName,
int appVersion,
char* contentTopicName,
char* encoding,
void* resp) {
WAKU_CALL( waku_content_topic(wakuCtx,
appName,
appVersion,
contentTopicName,
encoding,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuPubsubTopic(void* wakuCtx, char* topicName, void* resp) {
WAKU_CALL( waku_pubsub_topic(wakuCtx, topicName, (WakuCallBack) callback, resp) );
}
static void cGoWakuDefaultPubsubTopic(void* wakuCtx, void* resp) {
WAKU_CALL (waku_default_pubsub_topic(wakuCtx, (WakuCallBack) callback, resp));
}
static void cGoWakuRelayPublish(void* wakuCtx,
const char* pubSubTopic,
const char* jsonWakuMessage,
int timeoutMs,
void* resp) {
WAKU_CALL (waku_relay_publish(wakuCtx,
pubSubTopic,
jsonWakuMessage,
timeoutMs,
(WakuCallBack) callback,
resp));
}
static void cGoWakuRelaySubscribe(void* wakuCtx, char* pubSubTopic, void* resp) {
WAKU_CALL ( waku_relay_subscribe(wakuCtx,
pubSubTopic,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuRelayUnsubscribe(void* wakuCtx, char* pubSubTopic, void* resp) {
WAKU_CALL ( waku_relay_unsubscribe(wakuCtx,
pubSubTopic,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuConnect(void* wakuCtx, char* peerMultiAddr, int timeoutMs, void* resp) {
WAKU_CALL( waku_connect(wakuCtx,
peerMultiAddr,
timeoutMs,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuDialPeer(void* wakuCtx,
char* peerMultiAddr,
char* protocol,
int timeoutMs,
void* resp) {
WAKU_CALL( waku_dial_peer(wakuCtx,
peerMultiAddr,
protocol,
timeoutMs,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuDialPeerById(void* wakuCtx,
char* peerId,
char* protocol,
int timeoutMs,
void* resp) {
WAKU_CALL( waku_dial_peer_by_id(wakuCtx,
peerId,
protocol,
timeoutMs,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuDisconnectPeerById(void* wakuCtx, char* peerId, void* resp) {
WAKU_CALL( waku_disconnect_peer_by_id(wakuCtx,
peerId,
(WakuCallBack) callback,
resp) );
}
static void cGoWakuListenAddresses(void* wakuCtx, void* resp) {
WAKU_CALL (waku_listen_addresses(wakuCtx, (WakuCallBack) callback, resp) );
}
static void cGoWakuGetMyENR(void* ctx, void* resp) {
WAKU_CALL (waku_get_my_enr(ctx, (WakuCallBack) callback, resp) );
}
static void cGoWakuGetMyPeerId(void* ctx, void* resp) {
WAKU_CALL (waku_get_my_peerid(ctx, (WakuCallBack) callback, resp) );
}
static void cGoWakuPingPeer(void* ctx, char* peerAddr, int timeoutMs, void* resp) {
WAKU_CALL (waku_ping_peer(ctx, peerAddr, timeoutMs, (WakuCallBack) callback, resp) );
}
static void cGoWakuListPeersInMesh(void* ctx, char* pubSubTopic, void* resp) {
WAKU_CALL (waku_relay_get_num_peers_in_mesh(ctx, pubSubTopic, (WakuCallBack) callback, resp) );
}
static void cGoWakuGetNumConnectedRelayPeers(void* ctx, char* pubSubTopic, void* resp) {
WAKU_CALL (waku_relay_get_num_connected_peers(ctx, pubSubTopic, (WakuCallBack) callback, resp) );
}
static void cGoWakuGetConnectedPeers(void* wakuCtx, void* resp) {
WAKU_CALL (waku_get_connected_peers(wakuCtx, (WakuCallBack) callback, resp) );
}
static void cGoWakuGetPeerIdsFromPeerStore(void* wakuCtx, void* resp) {
WAKU_CALL (waku_get_peerids_from_peerstore(wakuCtx, (WakuCallBack) callback, resp) );
}
static void cGoWakuLightpushPublish(void* wakuCtx,
const char* pubSubTopic,
const char* jsonWakuMessage,
void* resp) {
WAKU_CALL (waku_lightpush_publish(wakuCtx,
pubSubTopic,
jsonWakuMessage,
(WakuCallBack) callback,
resp));
}
static void cGoWakuStoreQuery(void* wakuCtx,
const char* jsonQuery,
const char* peerAddr,
int timeoutMs,
void* resp) {
WAKU_CALL (waku_store_query(wakuCtx,
jsonQuery,
peerAddr,
timeoutMs,
(WakuCallBack) callback,
resp));
}
static void cGoWakuPeerExchangeQuery(void* wakuCtx,
uint64_t numPeers,
void* resp) {
WAKU_CALL (waku_peer_exchange_request(wakuCtx,
numPeers,
(WakuCallBack) callback,
resp));
}
static void cGoWakuGetPeerIdsByProtocol(void* wakuCtx,
const char* protocol,
void* resp) {
WAKU_CALL (waku_get_peerids_by_protocol(wakuCtx,
protocol,
(WakuCallBack) callback,
resp));
}
static void cGoWakuDnsDiscovery(void* wakuCtx,
const char* entTreeUrl,
const char* nameDnsServer,
int timeoutMs,
void* resp) {
WAKU_CALL (waku_dns_discovery(wakuCtx,
entTreeUrl,
nameDnsServer,
timeoutMs,
(WakuCallBack) callback,
resp));
}
*/
import "C"
import (
"context"
"crypto/ecdsa"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"runtime"
"strconv"
"strings"
"sync"
"testing"
"time"
"unsafe"
"github.com/jellydator/ttlcache/v3"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"go.uber.org/zap"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/time/rate"
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/core/metrics"
libp2pproto "github.com/libp2p/go-libp2p/core/protocol"
filterapi "github.com/waku-org/go-waku/waku/v2/api/filter"
"github.com/waku-org/go-waku/waku/v2/api/history"
"github.com/waku-org/go-waku/waku/v2/api/missing"
"github.com/waku-org/go-waku/waku/v2/api/publish"
"github.com/waku-org/go-waku/waku/v2/dnsdisc"
"github.com/waku-org/go-waku/waku/v2/onlinechecker"
"github.com/waku-org/go-waku/waku/v2/peermanager"
wps "github.com/waku-org/go-waku/waku/v2/peerstore"
"github.com/waku-org/go-waku/waku/v2/protocol"
"github.com/waku-org/go-waku/waku/v2/protocol/legacy_store"
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
"github.com/waku-org/go-waku/waku/v2/protocol/store"
storepb "github.com/waku-org/go-waku/waku/v2/protocol/store/pb"
"github.com/waku-org/go-waku/waku/v2/utils"
"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"
)
const messageQueueLimit = 1024
const requestTimeout = 30 * time.Second
const bootnodesQueryBackoffMs = 200
const bootnodesMaxRetries = 7
const cacheTTL = 20 * time.Minute
const maxRelayPeers = 300
const randomPeersKeepAliveInterval = 5 * time.Second
const allPeersKeepAliveInterval = 5 * time.Minute
type SentEnvelope struct {
Envelope *protocol.Envelope
PublishMethod publish.PublishMethod
}
type ErrorSendingEnvelope struct {
Error error
SentEnvelope SentEnvelope
}
type ITelemetryClient interface {
SetDeviceType(deviceType string)
PushSentEnvelope(ctx context.Context, sentEnvelope SentEnvelope)
PushErrorSendingEnvelope(ctx context.Context, errorSendingEnvelope ErrorSendingEnvelope)
PushPeerCount(ctx context.Context, peerCount int)
PushPeerConnFailures(ctx context.Context, peerConnFailures map[string]int)
PushMessageCheckSuccess(ctx context.Context, messageHash string)
PushMessageCheckFailure(ctx context.Context, messageHash string)
PushPeerCountByShard(ctx context.Context, peerCountByShard map[uint16]uint)
PushPeerCountByOrigin(ctx context.Context, peerCountByOrigin map[wps.Origin]uint)
}
type WakuMessageHash = string
type WakuPubsubTopic = string
type WakuContentTopic = string
type WakuConfig struct {
Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"`
NodeKey string `json:"key,omitempty"`
EnableRelay bool `json:"relay"`
LogLevel string `json:"logLevel"`
DnsDiscovery bool `json:"dnsDiscovery,omitempty"`
DnsDiscoveryUrl string `json:"dnsDiscoveryUrl,omitempty"`
MaxMessageSize string `json:"maxMessageSize,omitempty"`
Staticnodes []string `json:"staticnodes,omitempty"`
Discv5BootstrapNodes []string `json:"discv5BootstrapNodes,omitempty"`
Discv5Discovery bool `json:"discv5Discovery,omitempty"`
Discv5UdpPort uint16 `json:"discv5UdpPort,omitempty"`
ClusterID uint16 `json:"clusterId,omitempty"`
Shards []uint16 `json:"shards,omitempty"`
PeerExchange bool `json:"peerExchange,omitempty"`
PeerExchangeNode string `json:"peerExchangeNode,omitempty"`
TcpPort uint16 `json:"tcpPort,omitempty"`
}
// Waku represents a dark communication interface through the Ethereum
// network, using its very own P2P communication layer.
type Waku struct {
node *WakuNode
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
dnsDiscAsyncRetrievedSignal chan struct{}
// Filter-related
filters *common.Filters // Message filters installed with Subscribe function
filterManager *filterapi.FilterManager
privateKeys map[string]*ecdsa.PrivateKey // Private key storage
symKeys map[string][]byte // Symmetric key storage
keyMu sync.RWMutex // Mutex associated with key stores
envelopeCache *ttlcache.Cache[gethcommon.Hash, *common.ReceivedMessage] // Pool of envelopes currently tracked by this node
poolMu sync.RWMutex // Mutex to sync the message and expiration pools
bandwidthCounter *metrics.BandwidthCounter
protectedTopicStore *persistence.ProtectedTopicsStore
sendQueue *publish.MessageQueue
missingMsgVerifier *missing.MissingMessageVerifier
msgQueue chan *common.ReceivedMessage // Message queue for waku messages that havent been decoded
ctx context.Context
cancel context.CancelFunc
wg sync.WaitGroup
cfg *Config
wakuCfg *WakuConfig
options []node.WakuNodeOption
envelopeFeed event.Feed
storeMsgIDs map[gethcommon.Hash]bool // Map of the currently processing ids
storeMsgIDsMu sync.RWMutex
messageSender *publish.MessageSender
topicHealthStatusChan chan peermanager.TopicHealthStatus
connectionNotifChan chan node.PeerConnection
connStatusSubscriptions map[string]*types.ConnStatusSubscription
connStatusMu sync.Mutex
onlineChecker *onlinechecker.DefaultOnlineChecker
state connection.State
StorenodeCycle *history.StorenodeCycle
HistoryRetriever *history.HistoryRetriever
logger *zap.Logger
// NTP Synced timesource
timesource *timesource.NTPTimeSource
// seededBootnodesForDiscV5 indicates whether we manage to retrieve discovery
// bootnodes successfully
seededBootnodesForDiscV5 bool
// goingOnline is channel that notifies when connectivity has changed from offline to online
goingOnline chan struct{}
// discV5BootstrapNodes is the ENR to be used to fetch bootstrap nodes for discovery
discV5BootstrapNodes []string
onHistoricMessagesRequestFailed func([]byte, peer.AddrInfo, error)
onPeerStats func(types.ConnStatus)
statusTelemetryClient ITelemetryClient
defaultShardInfo protocol.RelayShards
}
func (w *Waku) SetStatusTelemetryClient(client ITelemetryClient) {
w.statusTelemetryClient = client
}
func newTTLCache() *ttlcache.Cache[gethcommon.Hash, *common.ReceivedMessage] {
cache := ttlcache.New[gethcommon.Hash, *common.ReceivedMessage](ttlcache.WithTTL[gethcommon.Hash, *common.ReceivedMessage](cacheTTL))
go cache.Start()
return cache
}
// New creates a WakuV2 client ready to communicate through the LibP2P network.
func New(nodeKey *ecdsa.PrivateKey, fleet string, cfg *Config, nwakuCfg *WakuConfig, logger *zap.Logger, appDB *sql.DB, ts *timesource.NTPTimeSource, onHistoricMessagesRequestFailed func([]byte, peer.AddrInfo, error), onPeerStats func(types.ConnStatus)) (*Waku, error) {
node, err := wakuNew(nodeKey,
fleet,
cfg,
nwakuCfg,
logger, appDB, ts, onHistoricMessagesRequestFailed,
onPeerStats)
if err != nil {
return nil, err
}
return node, nil
// TODO-nwaku
/*
var err error
if logger == nil {
logger, err = zap.NewDevelopment()
if err != nil {
return nil, err
}
}
if ts == nil {
ts = timesource.Default()
}
cfg = setDefaults(cfg)
if err = cfg.Validate(logger); err != nil {
return nil, err
}
logger.Info("starting wakuv2 with config", zap.Any("config", cfg))
ctx, cancel := context.WithCancel(context.Background())
waku := &Waku{
appDB: appDB,
cfg: cfg,
privateKeys: make(map[string]*ecdsa.PrivateKey),
symKeys: make(map[string][]byte),
envelopeCache: newTTLCache(),
msgQueue: make(chan *common.ReceivedMessage, messageQueueLimit),
topicHealthStatusChan: make(chan peermanager.TopicHealthStatus, 100),
connectionNotifChan: make(chan node.PeerConnection, 20),
connStatusSubscriptions: make(map[string]*types.ConnStatusSubscription),
ctx: ctx,
cancel: cancel,
wg: sync.WaitGroup{},
dnsAddressCache: make(map[string][]dnsdisc.DiscoveredNode),
dnsAddressCacheLock: &sync.RWMutex{},
dnsDiscAsyncRetrievedSignal: make(chan struct{}),
storeMsgIDs: make(map[gethcommon.Hash]bool),
timesource: ts,
storeMsgIDsMu: sync.RWMutex{},
logger: logger,
discV5BootstrapNodes: cfg.DiscV5BootstrapNodes,
onHistoricMessagesRequestFailed: onHistoricMessagesRequestFailed,
onPeerStats: onPeerStats,
onlineChecker: onlinechecker.NewDefaultOnlineChecker(false).(*onlinechecker.DefaultOnlineChecker),
sendQueue: publish.NewMessageQueue(1000, cfg.UseThrottledPublish),
}
waku.filters = common.NewFilters(waku.cfg.DefaultShardPubsubTopic, waku.logger)
waku.bandwidthCounter = metrics.NewBandwidthCounter()
if nodeKey == nil {
// No nodekey is provided, create an ephemeral key
nodeKey, err = crypto.GenerateKey()
if err != nil {
return nil, fmt.Errorf("failed to generate a random 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)
}
libp2pOpts := node.DefaultLibP2POptions
libp2pOpts = append(libp2pOpts, libp2p.BandwidthReporter(waku.bandwidthCounter))
libp2pOpts = append(libp2pOpts, libp2p.NATPortMap())
opts := []node.WakuNodeOption{
node.WithLibP2POptions(libp2pOpts...),
node.WithPrivateKey(nodeKey),
node.WithHostAddress(hostAddr),
node.WithConnectionNotification(waku.connectionNotifChan),
node.WithTopicHealthStatusChannel(waku.topicHealthStatusChan),
node.WithKeepAlive(randomPeersKeepAliveInterval, allPeersKeepAliveInterval),
node.WithLogger(logger),
node.WithLogLevel(logger.Level()),
node.WithClusterID(cfg.ClusterID),
node.WithMaxMsgSize(1024 * 1024),
}
if cfg.EnableDiscV5 {
bootnodes, err := waku.getDiscV5BootstrapNodes(waku.ctx, cfg.DiscV5BootstrapNodes, false)
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))
}
shards, err := protocol.TopicsToRelayShards(cfg.DefaultShardPubsubTopic)
if err != nil {
logger.Error("FATAL ERROR: failed to parse relay shards", zap.Error(err))
return nil, errors.New("failed to parse relay shard, invalid pubsubTopic configuration")
}
if len(shards) == 0 { //Hack so that tests don't fail. TODO: Need to remove this once tests are changed to use proper cluster and shard.
shardInfo := protocol.RelayShards{ClusterID: 0, ShardIDs: []uint16{0}}
shards = append(shards, shardInfo)
}
waku.defaultShardInfo = shards[0]
if cfg.LightClient {
opts = append(opts, node.WithWakuFilterLightNode())
waku.defaultShardInfo = shards[0]
opts = append(opts, node.WithMaxPeerConnections(cfg.DiscoveryLimit))
cfg.EnableStoreConfirmationForMessagesSent = false
//TODO: temporary work-around to improve lightClient connectivity, need to be removed once community sharding is implemented
opts = append(opts, node.WithShards(waku.defaultShardInfo.ShardIDs))
} else {
relayOpts := []pubsub.Option{
pubsub.WithMaxMessageSize(int(waku.cfg.MaxMessageSize)),
}
if testing.Testing() {
relayOpts = append(relayOpts, pubsub.WithEventTracer(waku))
}
opts = append(opts, node.WithWakuRelayAndMinPeers(waku.cfg.MinPeersForRelay, relayOpts...))
opts = append(opts, node.WithMaxPeerConnections(maxRelayPeers))
cfg.EnablePeerExchangeClient = true //Enabling this until discv5 issues are resolved. This will enable more peers to be connected for relay mesh.
cfg.EnableStoreConfirmationForMessagesSent = true
}
if cfg.EnableStore {
if appDB == nil {
return nil, errors.New("appDB is required for store")
}
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 !cfg.LightClient {
opts = append(opts, node.WithWakuFilterFullNode(filter.WithMaxSubscribers(20)))
opts = append(opts, node.WithLightPush(lightpush.WithRateLimiter(1, 1)))
}
if appDB != nil {
waku.protectedTopicStore, err = persistence.NewProtectedTopicsStore(logger, appDB)
if err != nil {
return nil, err
}
}
if cfg.EnablePeerExchangeServer {
opts = append(opts, node.WithPeerExchange(peer_exchange.WithRateLimiter(1, 1)))
}
waku.options = opts
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
}
/* TODO-nwaku
func (w *Waku) getDiscV5BootstrapNodes(ctx context.Context, addresses []string, useOnlyDnsDiscCache bool) ([]*enode.Node, error) {
wg := sync.WaitGroup{}
mu := sync.Mutex{}
var result []*enode.Node
w.seededBootnodesForDiscV5 = true
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 gocommon.LogOnPanic()
defer wg.Done()
if err := w.dnsDiscover(ctx, addr, retrieveENR, useOnlyDnsDiscCache); err != nil {
go func() {
defer gocommon.LogOnPanic()
w.retryDnsDiscoveryWithBackoff(ctx, addr, w.dnsDiscAsyncRetrievedSignal)
}()
}
}(addrString)
} else {
// It's a normal enr
bootnode, err := enode.Parse(enode.ValidSchemes, addrString)
if err != nil {
return nil, err
}
mu.Lock()
result = append(result, bootnode)
mu.Unlock()
}
}
wg.Wait()
if len(result) == 0 {
w.seededBootnodesForDiscV5 = false
}
return result, nil
}
type fnApplyToEachPeer func(d dnsdisc.DiscoveredNode, wg *sync.WaitGroup)
func (w *Waku) dnsDiscover(ctx context.Context, enrtreeAddress string, apply fnApplyToEachPeer, useOnlyCache bool) error {
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 && !useOnlyCache {
nameserver := w.cfg.Nameserver
resolver := w.cfg.Resolver
var opts []dnsdisc.DNSDiscoveryOption
if nameserver != "" {
opts = append(opts, dnsdisc.WithNameserver(nameserver))
}
if resolver != nil {
opts = append(opts, dnsdisc.WithResolver(resolver))
}
discoveredNodes, err := dnsdisc.RetrieveNodes(ctx, enrtreeAddress, opts...)
if err != nil {
w.logger.Warn("dns discovery error ", zap.Error(err))
return err
}
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()
return nil
}
func (w *Waku) retryDnsDiscoveryWithBackoff(ctx context.Context, addr string, successChan chan<- struct{}) {
retries := 0
for {
err := w.dnsDiscover(ctx, addr, func(d dnsdisc.DiscoveredNode, wg *sync.WaitGroup) {}, false)
if err == nil {
select {
case successChan <- struct{}{}:
default:
}
break
}
retries++
backoff := time.Second * time.Duration(math.Exp2(float64(retries)))
if backoff > time.Minute {
backoff = time.Minute
}
t := time.NewTimer(backoff)
select {
case <-w.ctx.Done():
t.Stop()
return
case <-t.C:
t.Stop()
}
}
}
*/
func (w *Waku) discoverAndConnectPeers() {
var addrsToConnect []multiaddr.Multiaddr
nameserver := w.cfg.Nameserver
if nameserver == "" {
nameserver = "8.8.8.8"
}
for _, addrString := range w.cfg.WakuNodes {
addrString := addrString
if strings.HasPrefix(addrString, "enrtree://") {
// Use DNS Discovery
ctx, _ := context.WithTimeout(w.ctx, requestTimeout)
res, err := w.node.DnsDiscovery(ctx, addrString, nameserver)
if err != nil {
w.logger.Error("could not obtain dns discovery peers for ClusterConfig.WakuNodes", zap.Error(err), zap.String("dnsDiscURL", addrString))
continue
}
for _, ma := range res {
addrsToConnect = append(addrsToConnect, ma)
}
} 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
}
addrsToConnect = append(addrsToConnect, addr)
}
}
// Now connect to all the Multiaddresses
for _, ma := range addrsToConnect {
ctx, _ := context.WithTimeout(w.ctx, requestTimeout)
w.node.Connect(ctx, ma)
}
}
func (w *Waku) connect(peerInfo peer.AddrInfo, enr *enode.Node, origin wps.Origin) {
defer gocommon.LogOnPanic()
// Connection will be prunned eventually by the connection manager if needed
// The peer connector in go-waku uses Connect, so it will execute identify as part of its
// TODO-nwaku
// TODO: is enr and origin required?
// TODO: this function is meant to add a node to a peer store so it can be picked up by the peer manager
// so probably we shouldn't connect directly but expose an AddPeer function in libwaku
ctx, cancel := context.WithTimeout(w.ctx, requestTimeout)
defer cancel()
addr := peerInfo.Addrs[0]
err := w.node.Connect(ctx, addr)
if err != nil {
w.logger.Error("couldn't connect to peer", zap.Error(err), zap.Stringer("peerID", peerInfo.ID))
}
}
/* TODO-nwaku
func (w *Waku) telemetryBandwidthStats(telemetryServerURL string) {
defer gocommon.LogOnPanic()
defer w.wg.Done()
if telemetryServerURL == "" {
return
}
telemetry := NewBandwidthTelemetryClient(w.logger, telemetryServerURL)
ticker := time.NewTicker(time.Second * 20)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
return
case <-ticker.C:
bandwidthPerProtocol := w.bandwidthCounter.GetBandwidthByProtocol()
w.bandwidthCounter.Reset()
go telemetry.PushProtocolStats(bandwidthPerProtocol)
}
}
}
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 gocommon.LogOnPanic()
defer w.wg.Done()
if !w.cfg.EnablePeerExchangeClient {
// Currently peer exchange client is only used for light nodes
return
}
ticker := time.NewTicker(time.Second * 5)
defer ticker.Stop()
for {
select {
case <-w.ctx.Done():
w.logger.Debug("Peer exchange loop stopped")
return
case <-ticker.C:
w.logger.Info("Running peer exchange loop")
// We select only the nodes discovered via DNS Discovery that support peer exchange
// We assume that those peers are running peer exchange according to infra config,
// If not, the peer selection process in go-waku will filter them out anyway
w.dnsAddressCacheLock.RLock()
var peers peer.IDSlice
for _, record := range w.dnsAddressCache {
for _, discoveredNode := range record {
if len(discoveredNode.PeerInfo.Addrs) == 0 {
continue
}
// Attempt to connect to the peers.
// Peers will be added to the libp2p peer store thanks to identify
go w.connect(discoveredNode.PeerInfo, discoveredNode.ENR, wps.DNSDiscovery)
peers = append(peers, discoveredNode.PeerID)
}
}
w.dnsAddressCacheLock.RUnlock()
if len(peers) != 0 {
err := w.node.PeerExchange().Request(w.ctx, w.cfg.DiscoveryLimit, peer_exchange.WithAutomaticPeerSelection(peers...),
peer_exchange.FilterByShard(int(w.defaultShardInfo.ClusterID), int(w.defaultShardInfo.ShardIDs[0])))
if err != nil {
w.logger.Error("couldnt request peers via peer exchange", zap.Error(err))
}
}
}
}
}
*/
func (w *Waku) GetPubsubTopic(topic string) string {
if topic == "" {
topic = w.cfg.DefaultShardPubsubTopic
}
return topic
}
func (w *Waku) unsubscribeFromPubsubTopicWithWakuRelay(topic string) error {
topic = w.GetPubsubTopic(topic)
return w.node.RelayUnsubscribe(topic)
}
func (w *Waku) subscribeToPubsubTopicWithWakuRelay(topic string, pubkey *ecdsa.PublicKey) error {
if w.cfg.LightClient {
return errors.New("only available for full nodes")
}
topic = w.GetPubsubTopic(topic)
/* TODO nwaku
if w.node.Relay().IsSubscribed(topic) {
return nil
}
if pubkey != nil {
err := w.node.Relay().AddSignedTopicValidator(topic, pubkey)
if err != nil {