go-waku/library/node.go

388 lines
9.6 KiB
Go
Raw Normal View History

2023-08-10 13:30:38 +00:00
package library
import (
"context"
"crypto/ecdsa"
"crypto/rand"
"database/sql"
"encoding/hex"
"errors"
"fmt"
"net"
"time"
"go.uber.org/zap/zapcore"
2022-10-20 15:14:46 +00:00
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/crypto"
2022-12-19 23:21:14 +00:00
"github.com/ethereum/go-ethereum/p2p/enode"
pubsub "github.com/libp2p/go-libp2p-pubsub"
2022-10-19 19:39:32 +00:00
"github.com/libp2p/go-libp2p/core/peer"
2023-02-16 16:17:52 +00:00
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"
2023-07-06 21:40:57 +00:00
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"
)
2023-08-10 13:30:38 +00:00
// 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
}
2023-08-10 13:30:38 +00:00
// 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 {
2023-08-10 13:30:38 +00:00
return errors.New("go-waku already initialized. stop it first")
}
config, err := getConfig(configJSON)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
hostAddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%d", *config.Host, *config.Port))
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
var prvKey *ecdsa.PrivateKey
if config.NodeKey != nil {
prvKey, err = crypto.HexToECDSA(*config.NodeKey)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
} else {
key, err := randomHex(32)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
prvKey, err = crypto.HexToECDSA(key)
if err != nil {
2023-08-10 13:30:38 +00:00
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 {
2023-08-10 13:30:38 +00:00
params := getGossipSubParams(config.GossipSubParams)
pubsubOpt = append(pubsubOpt, pubsub.WithGossipSubParams(params))
}
2023-07-06 18:20:16 +00:00
pubsubOpt = append(pubsubOpt, pubsub.WithSeenMessagesTTL(getSeenTTL(config)))
2023-03-14 10:38:56 +00:00
opts = append(opts, node.WithWakuRelayAndMinPeers(*config.MinPeersToPublish, pubsubOpt...))
}
2023-07-06 18:20:16 +00:00
if config.DNS4DomainName != "" {
opts = append(opts, node.WithDNS4Domain(config.DNS4DomainName))
2023-07-06 18:20:16 +00:00
}
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))
}
}
2023-06-22 18:55:51 +00:00
if *config.EnableLegacyFilter {
opts = append(opts, node.WithLegacyWakuFilter(false))
}
2023-06-22 18:55:51 +00:00
opts = append(opts, node.WithWakuFilterLightNode())
if *config.EnableStore {
var db *sql.DB
var migrationFn func(*sql.DB) error
2023-08-09 17:14:02 +00:00
db, migrationFn, err = dbutils.ExtractDBAndMigration(*config.DatabaseURL, dbutils.DBSettings{Vacuum: true}, utils.Logger())
if err != nil {
2023-08-10 13:30:38 +00:00
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 {
2023-08-10 13:30:38 +00:00
return err
}
opts = append(opts, node.WithMessageProvider(dbStore))
}
2022-12-19 23:21:14 +00:00
if *config.EnableDiscV5 {
var bootnodes []*enode.Node
for _, addr := range config.DiscV5BootstrapNodes {
bootnode, err := enode.Parse(enode.ValidSchemes, addr)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
2022-12-19 23:21:14 +00:00
}
bootnodes = append(bootnodes, bootnode)
}
opts = append(opts, node.WithDiscoveryV5(*config.DiscV5UDPPort, bootnodes, true))
2022-12-19 23:21:14 +00:00
}
wakuState.relayTopics = config.RelayTopics
lvl, err := zapcore.ParseLevel(*config.LogLevel)
2022-10-20 15:14:46 +00:00
if err != nil {
2023-08-10 13:30:38 +00:00
return err
2022-10-20 15:14:46 +00:00
}
opts = append(opts, node.WithLogLevel(lvl))
opts = append(opts, node.WithPrometheusRegisterer(prometheus.DefaultRegisterer))
2022-10-20 15:14:46 +00:00
2023-01-06 22:37:57 +00:00
w, err := node.New(opts...)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
wakuState.node = w
2023-08-10 13:30:38 +00:00
return nil
}
2023-08-10 13:30:38 +00:00
// Start starts the waku node
func Start() error {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return errWakuNodeNotReady
}
wakuState.ctx, wakuState.cancel = context.WithCancel(context.Background())
if err := wakuState.node.Start(wakuState.ctx); err != nil {
2023-08-10 13:30:38 +00:00
return err
}
if wakuState.node.DiscV5() != nil {
if err := wakuState.node.DiscV5().Start(context.Background()); err != nil {
wakuState.node.Stop()
2023-08-10 13:30:38 +00:00
return err
2023-01-04 18:46:22 +00:00
}
}
for _, topic := range wakuState.relayTopics {
err := relaySubscribe(topic)
if err != nil {
wakuState.node.Stop()
2023-08-10 13:30:38 +00:00
return err
}
}
2023-08-10 13:30:38 +00:00
return nil
}
2023-08-10 13:30:38 +00:00
// Stop stops a waku node
func Stop() error {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return errWakuNodeNotReady
}
wakuState.node.Stop()
wakuState.cancel()
wakuState.node = nil
2023-08-10 13:30:38 +00:00
return nil
}
2023-08-10 13:30:38 +00:00
// IsStarted is used to determine is a node is started or not
func IsStarted() bool {
return wakuState.node != nil
}
2023-08-10 13:30:38 +00:00
// PeerID is used to obtain the peer ID of the waku node
func PeerID() (string, error) {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return "", errWakuNodeNotReady
}
2023-08-10 13:30:38 +00:00
return wakuState.node.ID(), nil
}
2023-08-10 13:30:38 +00:00
// ListenAddresses returns the multiaddresses the wakunode is listening to
func ListenAddresses() (string, error) {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return "", errWakuNodeNotReady
}
var addresses []string
for _, addr := range wakuState.node.ListenAddresses() {
addresses = append(addresses, addr.String())
}
2023-08-10 13:30:38 +00:00
return marshalJSON(addresses)
}
2023-08-10 13:30:38 +00:00
// AddPeer adds a node multiaddress and protocol to the wakunode peerstore
func AddPeer(address string, protocolID string) (string, error) {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return "", errWakuNodeNotReady
}
ma, err := multiaddr.NewMultiaddr(address)
if err != nil {
2023-08-10 13:30:38 +00:00
return "", err
}
peerID, err := wakuState.node.AddPeer(ma, peerstore.Static, wakuState.relayTopics, libp2pProtocol.ID(protocolID))
2023-08-10 13:30:38 +00:00
if err != nil {
return "", err
}
2023-10-28 23:37:53 +00:00
return peerID.String(), nil
}
2023-08-10 13:30:38 +00:00
// 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 {
2023-08-10 13:30:38 +00:00
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()
}
2023-08-10 13:30:38 +00:00
return wakuState.node.DialPeer(ctx, address)
}
2023-08-10 13:30:38 +00:00
// 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 {
2023-08-10 13:30:38 +00:00
return errWakuNodeNotReady
}
var ctx context.Context
var cancel context.CancelFunc
pID, err := peer.Decode(peerID)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
if ms > 0 {
ctx, cancel = context.WithTimeout(context.Background(), time.Duration(int(ms))*time.Millisecond)
defer cancel()
} else {
ctx = context.Background()
}
2023-08-10 13:30:38 +00:00
return wakuState.node.DialPeerByID(ctx, pID)
}
2023-08-10 13:30:38 +00:00
// Disconnect closes a connection to a known peer by peerID
func Disconnect(peerID string) error {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return errWakuNodeNotReady
}
pID, err := peer.Decode(peerID)
if err != nil {
2023-08-10 13:30:38 +00:00
return err
}
2023-08-10 13:30:38 +00:00
return wakuState.node.ClosePeerById(pID)
}
2023-08-10 13:30:38 +00:00
// PeerCnt returns the number of connected peers
func PeerCnt() (int, error) {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return 0, errWakuNodeNotReady
}
2023-08-10 13:30:38 +00:00
return wakuState.node.PeerCount(), nil
}
2023-08-10 13:30:38 +00:00
// ContentTopic creates a content topic string according to RFC 23
func ContentTopic(applicationName string, applicationVersion int, contentTopicName string, encoding string) string {
contentTopic, _ := protocol.NewContentTopic(applicationName, uint32(applicationVersion), contentTopicName, encoding)
return contentTopic.String()
}
2023-08-10 13:30:38 +00:00
// 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(),
}
}
2023-08-10 13:30:38 +00:00
// Peers retrieves the list of peers known by the waku node
func Peers() (string, error) {
if wakuState.node == nil {
2023-08-10 13:30:38 +00:00
return "", errWakuNodeNotReady
}
peers, err := wakuState.node.Peers()
2023-08-10 13:30:38 +00:00
if err != nil {
return "", err
}
2023-10-28 23:37:53 +00:00
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
}
2023-08-10 13:30:38 +00:00
return marshalJSON(peers)
}