go-waku/examples/noise/main.go

225 lines
5.9 KiB
Go
Raw Permalink Normal View History

2022-12-21 18:47:43 +00:00
package main
import (
"context"
"encoding/hex"
"fmt"
"net"
"net/url"
2023-02-20 14:53:01 +00:00
"noise/pb"
2022-12-21 18:47:43 +00:00
"os"
"os/signal"
"sync"
"syscall"
"time"
logging "github.com/ipfs/go-log/v2"
2023-05-19 20:20:49 +00:00
"github.com/libp2p/go-libp2p/core/peer"
2022-12-21 18:47:43 +00:00
n "github.com/waku-org/go-noise"
"github.com/waku-org/go-waku/waku/v2/dnsdisc"
"github.com/waku-org/go-waku/waku/v2/node"
"github.com/waku-org/go-waku/waku/v2/protocol"
2022-12-21 18:47:43 +00:00
"github.com/waku-org/go-waku/waku/v2/protocol/noise"
"github.com/waku-org/go-waku/waku/v2/protocol/relay"
2022-12-21 18:47:43 +00:00
"github.com/waku-org/go-waku/waku/v2/timesource"
"github.com/waku-org/go-waku/waku/v2/utils"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
)
2023-02-20 14:53:01 +00:00
var log = utils.Logger().Named("noise")
2022-12-21 18:47:43 +00:00
func main() {
// Removing noisy logs
lvl, err := logging.LevelFromString("error")
if err != nil {
panic(err)
}
logging.SetAllLoggers(lvl)
hostAddr, _ := net.ResolveTCPAddr("tcp", fmt.Sprint("0.0.0.0:0"))
2023-02-20 14:53:01 +00:00
wakuNode, err := node.New(
2022-12-21 18:47:43 +00:00
node.WithHostAddress(hostAddr),
node.WithNTP(),
node.WithWakuRelay(),
)
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("could not instantiate waku", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
2023-02-20 14:53:01 +00:00
if err := wakuNode.Start(context.Background()); err != nil {
log.Error("could not start waku", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
discoverFleetNodes(wakuNode)
myStaticKey, _ := n.DH25519.GenerateKeypair()
myEphemeralKey, _ := n.DH25519.GenerateKeypair()
relayMessenger, err := noise.NewWakuRelayMessenger(context.Background(), wakuNode.Relay(), nil, timesource.NewDefaultClock())
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("could not create relay messenger", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
pairingObj, err := noise.NewPairing(myStaticKey, myEphemeralKey, noise.WithDefaultResponderParameters(), relayMessenger, utils.Logger())
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("could not create pairing object", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
qrString, qrMessageNameTag := pairingObj.PairingInfo()
2023-02-20 14:53:01 +00:00
qrURL := "messageNameTag=" + url.QueryEscape(hex.EncodeToString(qrMessageNameTag[:])) + "&qrCode=" + url.QueryEscape(qrString)
2022-12-21 18:47:43 +00:00
wg := sync.WaitGroup{}
// Execute in separate go routine
wg.Add(1)
go func() {
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
defer cancel()
err := pairingObj.Execute(ctx)
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("could not perform handshake", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
}()
// Confirmation is done by manually
wg.Add(1)
go func() {
defer wg.Done()
authCode := <-pairingObj.AuthCode()
fmt.Println("=============================================")
fmt.Println("TODO: ask to confirm pairing. Automaticaly confirming authcode", authCode)
fmt.Println("=============================================")
err := pairingObj.ConfirmAuthCode(true)
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("could not confirm authcode", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
}()
fmt.Println("=============================================================================")
2023-02-20 14:53:01 +00:00
fmt.Printf("Browse https://examples.waku.org/noise-js/?%s\n", qrURL)
2022-12-21 18:47:43 +00:00
fmt.Println("=============================================================================")
wg.Wait()
// Securely transferring messages
if pairingObj.HandshakeComplete() {
go writeLoop(context.Background(), wakuNode, pairingObj)
go readLoop(context.Background(), wakuNode, pairingObj)
}
// 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()
}
func discoverFleetNodes(wakuNode *node.WakuNode) error {
log.Info("Connecting to test fleet...")
2024-03-11 13:22:48 +00:00
dnsDiscoveryUrl := "enrtree://AOGYWMBYOUIMOENHXCHILPKY3ZRFEULMFI4DOM442QSZ73TT2A7VI@test.waku.nodes.status.im"
2022-12-21 18:47:43 +00:00
nodes, err := dnsdisc.RetrieveNodes(context.Background(), dnsDiscoveryUrl)
if err != nil {
return err
}
2023-05-19 20:20:49 +00:00
var peerInfo []peer.AddrInfo
2022-12-21 18:47:43 +00:00
for _, n := range nodes {
2023-05-19 20:20:49 +00:00
peerInfo = append(peerInfo, n.PeerInfo)
2022-12-21 18:47:43 +00:00
}
wg := sync.WaitGroup{}
2023-05-19 20:20:49 +00:00
wg.Add(len(peerInfo))
for _, p := range peerInfo {
go func(p peer.AddrInfo) {
2022-12-21 18:47:43 +00:00
defer wg.Done()
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(10)*time.Second)
defer cancel()
2023-05-19 20:20:49 +00:00
err = wakuNode.DialPeerWithInfo(ctx, p)
2022-12-21 18:47:43 +00:00
if err != nil {
2023-05-19 20:20:49 +00:00
log.Error("could not connect", zap.String("peerID", p.ID.String()), zap.Error(err))
2022-12-21 18:47:43 +00:00
} else {
2023-05-19 20:20:49 +00:00
log.Info("connected", zap.String("peerID", p.ID.String()))
2022-12-21 18:47:43 +00:00
}
2023-05-19 20:20:49 +00:00
}(p)
2022-12-21 18:47:43 +00:00
}
wg.Wait()
return nil
}
func writeLoop(ctx context.Context, wakuNode *node.WakuNode, pairingObj *noise.Pairing) {
2023-02-20 14:53:01 +00:00
cnt := 0
2022-12-21 18:47:43 +00:00
for {
time.Sleep(4 * time.Second)
2023-02-20 14:53:01 +00:00
cnt++
chatMessage := &pb.Chat2Message{
2022-12-21 18:47:43 +00:00
Timestamp: uint64(wakuNode.Timesource().Now().Unix()),
Nick: "go-waku",
2023-02-20 14:53:01 +00:00
Payload: []byte(fmt.Sprintf("Hello World! #%d", cnt)),
2022-12-21 18:47:43 +00:00
}
chatMessageBytes, err := proto.Marshal(chatMessage)
if err != nil {
log.Error("Error encoding message: ", zap.Error(err))
continue
}
msg, err := pairingObj.Encrypt(chatMessageBytes)
if err != nil {
log.Error("error encrypting message", zap.Error(err))
continue
}
msg.Timestamp = utils.GetUnixEpoch(wakuNode.Timesource())
2022-12-21 18:47:43 +00:00
_, err = wakuNode.Relay().Publish(ctx, msg, relay.WithDefaultPubsubTopic())
2022-12-21 18:47:43 +00:00
if err != nil {
log.Error("Error sending a message", zap.Error(err))
}
}
}
func readLoop(ctx context.Context, wakuNode *node.WakuNode, pairingObj *noise.Pairing) {
sub, err := wakuNode.Relay().Subscribe(ctx, protocol.NewContentFilter(relay.DefaultWakuTopic))
2022-12-21 18:47:43 +00:00
if err != nil {
2023-02-20 14:53:01 +00:00
log.Error("Could not subscribe", zap.Error(err))
2022-12-21 18:47:43 +00:00
return
}
for value := range sub[0].Ch {
2022-12-21 18:47:43 +00:00
if value.Message().ContentTopic != pairingObj.ContentTopic {
continue
}
msgBytes, err := pairingObj.Decrypt(value.Message())
if err != nil {
log.Debug("Error decoding a message", zap.Error(err))
continue
}
2023-02-20 14:53:01 +00:00
msg := &pb.Chat2Message{}
2022-12-21 18:47:43 +00:00
if err := proto.Unmarshal(msgBytes, msg); err != nil {
log.Error("Error decoding a message", zap.Error(err))
continue
}
fmt.Println("Received msg from ", msg.Nick, " - "+string(msg.Payload))
}
}