go-waku/examples/basic-relay/main.go

225 lines
5.6 KiB
Go
Raw Permalink Normal View History

2021-04-04 19:33:21 +00:00
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
2021-04-04 19:33:21 +00:00
"fmt"
"net"
"os"
"os/signal"
"syscall"
"time"
"github.com/ethereum/go-ethereum/crypto"
2024-02-01 10:08:01 +00:00
"github.com/multiformats/go-multiaddr"
cli "github.com/urfave/cli/v2"
"github.com/urfave/cli/v2/altsrc"
2024-02-01 10:08:01 +00:00
"github.com/waku-org/go-waku/logging"
"github.com/waku-org/go-waku/waku/v2/node"
2022-12-21 18:47:43 +00:00
"github.com/waku-org/go-waku/waku/v2/payload"
2024-02-01 10:08:01 +00:00
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/pb"
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
"github.com/waku-org/go-waku/waku/v2/utils"
"go.uber.org/zap"
2024-02-01 10:08:01 +00:00
"go.uber.org/zap/zapcore"
"google.golang.org/protobuf/proto"
2021-04-04 19:33:21 +00:00
)
var log = utils.Logger().Named("basic-relay")
var ClusterID = altsrc.NewUintFlag(&cli.UintFlag{
Name: "cluster-id",
Value: 1,
Usage: "Cluster id that the node is running in. Node in a different cluster id is disconnected.",
Destination: &clusterID,
})
var Shard = altsrc.NewUintFlag(&cli.UintFlag{
Name: "shard",
Value: 0,
Usage: "shard that the node wants to subscribe and publish to.",
Destination: &shard,
})
2024-02-01 10:08:01 +00:00
var StaticNode = altsrc.NewStringFlag(&cli.StringFlag{
Name: "maddr",
Usage: "multiaddress of static node to connect to.",
Destination: &multiaddress,
})
var clusterID, shard uint
var pubsubTopicStr string
2024-02-01 10:08:01 +00:00
var multiaddress string
2021-04-04 19:33:21 +00:00
func main() {
cliFlags := []cli.Flag{
ClusterID,
Shard,
2024-02-01 10:08:01 +00:00
StaticNode,
}
app := &cli.App{
Name: "basic-relay-example",
Flags: cliFlags,
Action: func(c *cli.Context) error {
err := Execute()
if err != nil {
utils.Logger().Error("failure while executing wakunode", zap.Error(err))
switch e := err.(type) {
case cli.ExitCoder:
return e
case error:
return cli.Exit(err.Error(), 1)
}
}
return nil
},
}
err := app.Run(os.Args)
if err != nil {
panic(err)
}
}
func Execute() error {
var cTopic, err = protocol.NewContentTopic("basic-relay", "1", "test", "proto")
if err != nil {
fmt.Println("Invalid contentTopic")
return errors.New("invalid contentTopic")
}
contentTopic := cTopic.String()
hostAddr, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:0")
2021-04-04 19:33:21 +00:00
key, err := randomHex(32)
if err != nil {
log.Error("Could not generate random key", zap.Error(err))
return err
2021-04-04 19:33:21 +00:00
}
prvKey, err := crypto.HexToECDSA(key)
2021-11-02 00:05:36 +00:00
if err != nil {
log.Error("Could not convert hex into ecdsa key", zap.Error(err))
return err
2021-11-02 00:05:36 +00:00
}
2021-04-04 19:33:21 +00:00
ctx := context.Background()
2023-01-06 22:37:57 +00:00
wakuNode, err := node.New(
node.WithPrivateKey(prvKey),
2021-11-17 16:19:42 +00:00
node.WithHostAddress(hostAddr),
2022-12-09 03:08:04 +00:00
node.WithNTP(),
node.WithWakuRelay(),
node.WithClusterID(uint16(clusterID)),
2024-02-01 10:08:01 +00:00
node.WithLogLevel(zapcore.DebugLevel),
)
2021-10-05 02:13:54 +00:00
if err != nil {
log.Error("Error creating wakunode", zap.Error(err))
return err
2021-10-05 02:13:54 +00:00
}
2023-01-06 22:37:57 +00:00
if err := wakuNode.Start(ctx); err != nil {
log.Error("Error starting wakunode", zap.Error(err))
return err
}
//Populate pubsubTopic if shard is specified. Otherwise it is derived via autosharing algorithm
if shard != 0 {
pubsubTopic := protocol.NewStaticShardingPubsubTopic(uint16(clusterID), uint16(shard))
pubsubTopicStr = pubsubTopic.String()
2021-10-05 02:13:54 +00:00
}
2021-04-04 19:33:21 +00:00
2024-02-01 10:08:01 +00:00
if multiaddress != "" {
maddr, err := multiaddr.NewMultiaddr(multiaddress)
if err != nil {
log.Info("Error decoding multiaddr ", zap.Error(err))
}
_, err = wakuNode.AddPeer(maddr, wps.Static,
[]string{pubsubTopicStr}, relay.WakuRelayID_v200)
if err != nil {
log.Info("Error adding filter peer on light node ", zap.Error(err))
}
}
go writeLoop(ctx, wakuNode, contentTopic)
go readLoop(ctx, wakuNode, contentTopic)
2021-04-04 19:33:21 +00:00
// Wait for a SIGINT or SIGTERM signal
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
<-ch
fmt.Println("\n\n\nReceived signal, shutting down...")
// shut the node down
wakuNode.Stop()
return nil
2021-04-04 19:33:21 +00:00
}
func randomHex(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func write(ctx context.Context, wakuNode *node.WakuNode, contentTopic string, msgContent string) {
2021-04-04 19:33:21 +00:00
var version uint32 = 0
2022-12-21 18:47:43 +00:00
p := new(payload.Payload)
2021-04-11 23:45:42 +00:00
p.Data = []byte(wakuNode.ID() + ": " + msgContent)
2022-12-21 18:47:43 +00:00
p.Key = &payload.KeyInfo{Kind: payload.None}
2021-04-11 23:45:42 +00:00
payload, err := p.Encode(version)
2021-11-02 00:05:36 +00:00
if err != nil {
log.Error("Error encoding the payload", zap.Error(err))
2021-11-02 00:05:36 +00:00
return
}
2021-04-11 23:45:42 +00:00
2021-04-22 00:12:51 +00:00
msg := &pb.WakuMessage{
2021-04-04 19:33:21 +00:00
Payload: payload,
Version: proto.Uint32(version),
2023-02-09 12:53:37 +00:00
ContentTopic: contentTopic,
Timestamp: utils.GetUnixEpoch(wakuNode.Timesource()),
2021-04-04 19:33:21 +00:00
}
2024-02-01 10:08:01 +00:00
hash, err := wakuNode.Relay().Publish(ctx, msg, relay.WithPubSubTopic(pubsubTopicStr))
2021-04-04 19:33:21 +00:00
if err != nil {
log.Error("Error sending a message", zap.Error(err))
2021-04-04 19:33:21 +00:00
}
2024-05-03 16:07:03 +00:00
log.Info("Published msg,", zap.String("data", string(msg.Payload)), logging.HexBytes("hash", hash.Bytes()))
2021-04-04 19:33:21 +00:00
}
func writeLoop(ctx context.Context, wakuNode *node.WakuNode, contentTopic string) {
2021-04-04 19:33:21 +00:00
for {
time.Sleep(2 * time.Second)
write(ctx, wakuNode, contentTopic, "Hello world!")
2021-04-04 19:33:21 +00:00
}
}
func readLoop(ctx context.Context, wakuNode *node.WakuNode, contentTopic string) {
sub, err := wakuNode.Relay().Subscribe(ctx, protocol.NewContentFilter(pubsubTopicStr, contentTopic))
2021-04-04 19:33:21 +00:00
if err != nil {
log.Error("Could not subscribe", zap.Error(err))
2021-04-04 19:33:21 +00:00
return
}
for envelope := range sub[0].Ch {
2023-02-09 12:53:37 +00:00
if envelope.Message().ContentTopic != contentTopic {
continue
}
payload, err := payload.DecodePayload(envelope.Message(), &payload.KeyInfo{Kind: payload.None})
2021-04-04 19:33:21 +00:00
if err != nil {
2023-02-09 12:53:37 +00:00
log.Error("Error decoding payload", zap.Error(err))
continue
2021-04-04 19:33:21 +00:00
}
log.Info("Received msg, ", zap.String("data", string(payload.Data)))
2021-04-04 19:33:21 +00:00
}
}