/
node.go
383 lines (310 loc) · 9.6 KB
/
node.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
package library
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net"
"time"
"go.uber.org/zap/zapcore"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"github.com/libp2p/go-libp2p/core/peer"
libp2pProtocol "github.com/libp2p/go-libp2p/core/protocol"
"github.com/multiformats/go-multiaddr"
"github.com/prometheus/client_golang/prometheus"
"github.com/waku-org/go-waku/waku/persistence"
dbutils "github.com/waku-org/go-waku/waku/persistence/utils"
"github.com/waku-org/go-waku/waku/v2/node"
"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/pb"
"github.com/waku-org/go-waku/waku/v2/utils"
)
// WakuState represents the state of the waku node
type WakuState struct {
ctx context.Context
cancel context.CancelFunc
node *node.WakuNode
relayTopics []string
}
var wakuState WakuState
var errWakuNodeNotReady = errors.New("go-waku not initialized")
func randomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
// NewNode initializes a waku node. Receives a JSON string containing the configuration, and use default values for those config items not specified
func NewNode(configJSON string) error {
if wakuState.node != nil {
return errors.New("go-waku already initialized. stop it first")
}
config, err := getConfig(configJSON)
if err != nil {
return err
}
hostAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", *config.Host, *config.Port))
if err != nil {
return err
}
var prvKey *ecdsa.PrivateKey
if config.NodeKey != nil {
prvKey, err = crypto.HexToECDSA(*config.NodeKey)
if err != nil {
return err
}
} else {
key, err := randomHex(32)
if err != nil {
return err
}
prvKey, err = crypto.HexToECDSA(key)
if err != nil {
return err
}
}
opts := []node.WakuNodeOption{
node.WithPrivateKey(prvKey),
node.WithHostAddress(hostAddr),
node.WithKeepAlive(time.Duration(*config.KeepAliveInterval) * time.Second),
}
if *config.EnableRelay {
var pubsubOpt []pubsub.Option
if config.GossipSubParams != nil {
params := getGossipSubParams(config.GossipSubParams)
pubsubOpt = append(pubsubOpt, pubsub.WithGossipSubParams(params))
}
pubsubOpt = append(pubsubOpt, pubsub.WithSeenMessagesTTL(getSeenTTL(config)))
opts = append(opts, node.WithWakuRelayAndMinPeers(*config.MinPeersToPublish, pubsubOpt...))
}
if config.DNS4DomainName != "" {
opts = append(opts, node.WithDNS4Domain(config.DNS4DomainName))
}
if config.Websockets.Enabled {
if config.Websockets.Secure {
if config.DNS4DomainName == "" {
utils.Logger().Warn("using secure websockets without a dns4 domain name might indicate a misconfiguration")
}
opts = append(opts, node.WithSecureWebsockets(config.Websockets.Host, *config.Websockets.Port, config.Websockets.CertPath, config.Websockets.KeyPath))
} else {
opts = append(opts, node.WithWebsockets(config.Websockets.Host, *config.Websockets.Port))
}
}
if *config.EnableLegacyFilter {
opts = append(opts, node.WithLegacyWakuFilter(false))
}
opts = append(opts, node.WithWakuFilterLightNode())
if *config.EnableStore {
var db *sql.DB
var migrationFn func(*sql.DB) error
db, migrationFn, err = dbutils.ExtractDBAndMigration(*config.DatabaseURL, dbutils.DBSettings{}, utils.Logger())
if err != nil {
return err
}
opts = append(opts, node.WithWakuStore())
dbStore, err := persistence.NewDBStore(prometheus.DefaultRegisterer, utils.Logger(),
persistence.WithDB(db),
persistence.WithMigrations(migrationFn),
persistence.WithRetentionPolicy(*config.RetentionMaxMessages, time.Duration(*config.RetentionTimeSeconds)*time.Second),
)
if err != nil {
return err
}
opts = append(opts, node.WithMessageProvider(dbStore))
}
if *config.EnableDiscV5 {
discoveredNodes := node.GetNodesFromDNSDiscovery(utils.Logger(), context.TODO(), config.DNSDiscoveryNameServer, config.DNSDiscoveryURLs)
discv5Opts, err := node.GetDiscv5Option(discoveredNodes, config.DiscV5BootstrapNodes, *config.DiscV5UDPPort, true)
if err != nil {
return err
}
opts = append(opts, discv5Opts)
}
wakuState.relayTopics = config.RelayTopics
lvl, err := zapcore.ParseLevel(*config.LogLevel)
if err != nil {
return err
}
opts = append(opts, node.WithLogLevel(lvl))
opts = append(opts, node.WithPrometheusRegisterer(prometheus.DefaultRegisterer))
w, err := node.New(opts...)
if err != nil {
return err
}
wakuState.node = w
return nil
}
// Start starts the waku node
func Start() error {
if wakuState.node == nil {
return errWakuNodeNotReady
}
wakuState.ctx, wakuState.cancel = context.WithCancel(context.Background())
if err := wakuState.node.Start(wakuState.ctx); err != nil {
return err
}
if wakuState.node.DiscV5() != nil {
if err := wakuState.node.DiscV5().Start(context.Background()); err != nil {
wakuState.node.Stop()
return err
}
}
for _, topic := range wakuState.relayTopics {
err := relaySubscribe(topic)
if err != nil {
wakuState.node.Stop()
return err
}
}
return nil
}
// Stop stops a waku node
func Stop() error {
if wakuState.node == nil {
return errWakuNodeNotReady
}
wakuState.node.Stop()
wakuState.cancel()
wakuState.node = nil
return nil
}
// IsStarted is used to determine is a node is started or not
func IsStarted() bool {
return wakuState.node != nil
}
// PeerID is used to obtain the peer ID of the waku node
func PeerID() (string, error) {
if wakuState.node == nil {
return "", errWakuNodeNotReady
}
return wakuState.node.ID(), nil
}
// ListenAddresses returns the multiaddresses the wakunode is listening to
func ListenAddresses() (string, error) {
if wakuState.node == nil {
return "", errWakuNodeNotReady
}
var addresses []string
for _, addr := range wakuState.node.ListenAddresses() {
addresses = append(addresses, addr.String())
}
return marshalJSON(addresses)
}
// AddPeer adds a node multiaddress and protocol to the wakunode peerstore
func AddPeer(address string, protocolID string) (string, error) {
if wakuState.node == nil {
return "", errWakuNodeNotReady
}
ma, err := multiaddr.NewMultiaddr(address)
if err != nil {
return "", err
}
peerID, err := wakuState.node.AddPeer(ma, peerstore.Static, wakuState.relayTopics, libp2pProtocol.ID(protocolID))
if err != nil {
return "", err
}
return peerID.String(), nil
}
// Connect is used to connect to a peer at multiaddress. if ms > 0, cancel the function execution if it takes longer than N milliseconds
func Connect(address string, ms int) error {
if wakuState.node == nil {
return errWakuNodeNotReady
}
var ctx context.Context
var cancel context.CancelFunc
if ms > 0 {
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
defer cancel()
} else {
ctx = context.Background()
}
return wakuState.node.DialPeer(ctx, address)
}
// ConnectPeerID is usedd to connect to a known peer by peerID. if ms > 0, cancel the function execution if it takes longer than N milliseconds
func ConnectPeerID(peerID string, ms int) error {
if wakuState.node == nil {
return errWakuNodeNotReady
}
var ctx context.Context
var cancel context.CancelFunc
pID, err := peer.Decode(peerID)
if err != nil {
return err
}
if ms > 0 {
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
defer cancel()
} else {
ctx = context.Background()
}
return wakuState.node.DialPeerByID(ctx, pID)
}
// Disconnect closes a connection to a known peer by peerID
func Disconnect(peerID string) error {
if wakuState.node == nil {
return errWakuNodeNotReady
}
pID, err := peer.Decode(peerID)
if err != nil {
return err
}
return wakuState.node.ClosePeerById(pID)
}
// PeerCnt returns the number of connected peers
func PeerCnt() (int, error) {
if wakuState.node == nil {
return 0, errWakuNodeNotReady
}
return wakuState.node.PeerCount(), nil
}
// ContentTopic creates a content topic string according to RFC 23
func ContentTopic(applicationName string, applicationVersion string, contentTopicName string, encoding string) string {
contentTopic, _ := protocol.NewContentTopic(applicationName, applicationVersion, contentTopicName, encoding)
return contentTopic.String()
}
// DefaultPubsubTopic returns the default pubsub topic used in waku2: /waku/2/default-waku/proto
func DefaultPubsubTopic() string {
return protocol.DefaultPubsubTopic{}.String()
}
type subscriptionMsg struct {
MessageID string `json:"messageId"`
PubsubTopic string `json:"pubsubTopic"`
Message *pb.WakuMessage `json:"wakuMessage"`
}
func toSubscriptionMessage(msg *protocol.Envelope) *subscriptionMsg {
return &subscriptionMsg{
MessageID: hexutil.Encode(msg.Hash()),
PubsubTopic: msg.PubsubTopic(),
Message: msg.Message(),
}
}
// Peers retrieves the list of peers known by the waku node
func Peers() (string, error) {
if wakuState.node == nil {
return "", errWakuNodeNotReady
}
peers, err := wakuState.node.Peers()
if err != nil {
return "", err
}
for _, p := range peers {
addrs := []multiaddr.Multiaddr{}
for i := range p.Addrs {
// Filtering out SNI addresses due to https://github.com/waku-org/waku-rust-bindings/issues/66
// TODO: once https://github.com/multiformats/rust-multiaddr/issues/88 is implemented, remove this
_, err := p.Addrs[i].ValueForProtocol(multiaddr.P_SNI)
if err != nil {
addrs = append(addrs, p.Addrs[i])
}
}
p.Addrs = addrs
}
return marshalJSON(peers)
}