feat: use correct port field, get free ports and uncomment some functions (#6200)

This commit is contained in:
richΛrd 2024-12-12 08:24:51 -04:00
parent 88e7a58016
commit a87bed5abc
1 changed files with 64 additions and 42 deletions

View File

@ -313,6 +313,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"net"
"runtime" "runtime"
"strconv" "strconv"
"strings" "strings"
@ -408,8 +409,7 @@ type WakuContentTopic = string
type WakuConfig struct { type WakuConfig struct {
Host string `json:"host,omitempty"` Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"` NodeKey string `json:"nodekey,omitempty"`
NodeKey string `json:"key,omitempty"`
EnableRelay bool `json:"relay"` EnableRelay bool `json:"relay"`
LogLevel string `json:"logLevel"` LogLevel string `json:"logLevel"`
DnsDiscovery bool `json:"dnsDiscovery,omitempty"` DnsDiscovery bool `json:"dnsDiscovery,omitempty"`
@ -418,12 +418,12 @@ type WakuConfig struct {
Staticnodes []string `json:"staticnodes,omitempty"` Staticnodes []string `json:"staticnodes,omitempty"`
Discv5BootstrapNodes []string `json:"discv5BootstrapNodes,omitempty"` Discv5BootstrapNodes []string `json:"discv5BootstrapNodes,omitempty"`
Discv5Discovery bool `json:"discv5Discovery,omitempty"` Discv5Discovery bool `json:"discv5Discovery,omitempty"`
Discv5UdpPort uint16 `json:"discv5UdpPort,omitempty"` Discv5UdpPort int `json:"discv5UdpPort,omitempty"`
ClusterID uint16 `json:"clusterId,omitempty"` ClusterID uint16 `json:"clusterId,omitempty"`
Shards []uint16 `json:"shards,omitempty"` Shards []uint16 `json:"shards,omitempty"`
PeerExchange bool `json:"peerExchange,omitempty"` PeerExchange bool `json:"peerExchange,omitempty"`
PeerExchangeNode string `json:"peerExchangeNode,omitempty"` PeerExchangeNode string `json:"peerExchangeNode,omitempty"`
TcpPort uint16 `json:"tcpPort,omitempty"` TcpPort int `json:"tcpPort,omitempty"`
} }
// Waku represents a dark communication interface through the Ethereum // Waku represents a dark communication interface through the Ethereum
@ -533,18 +533,6 @@ func New(nodeKey *ecdsa.PrivateKey, fleet string, cfg *Config, nwakuCfg *WakuCon
// TODO-nwaku // 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) cfg = setDefaults(cfg)
if err = cfg.Validate(logger); err != nil { if err = cfg.Validate(logger); err != nil {
return nil, err return nil, err
@ -583,19 +571,6 @@ func New(nodeKey *ecdsa.PrivateKey, fleet string, cfg *Config, nwakuCfg *WakuCon
waku.bandwidthCounter = metrics.NewBandwidthCounter() 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 := node.DefaultLibP2POptions
libp2pOpts = append(libp2pOpts, libp2p.BandwidthReporter(waku.bandwidthCounter)) libp2pOpts = append(libp2pOpts, libp2p.BandwidthReporter(waku.bandwidthCounter))
libp2pOpts = append(libp2pOpts, libp2p.NATPortMap()) libp2pOpts = append(libp2pOpts, libp2p.NATPortMap())
@ -991,9 +966,6 @@ func (w *Waku) subscribeToPubsubTopicWithWakuRelay(topic string, pubkey *ecdsa.P
topic = w.GetPubsubTopic(topic) topic = w.GetPubsubTopic(topic)
/* TODO nwaku /* TODO nwaku
if w.node.Relay().IsSubscribed(topic) {
return nil
}
if pubkey != nil { if pubkey != nil {
err := w.node.Relay().AddSignedTopicValidator(topic, pubkey) err := w.node.Relay().AddSignedTopicValidator(topic, pubkey)
@ -1375,21 +1347,12 @@ func (w *Waku) Start() error {
return fmt.Errorf("failed to start nwaku node: %v", err) return fmt.Errorf("failed to start nwaku node: %v", err)
} }
/* TODO-nwaku
if w.ctx == nil { if w.ctx == nil {
w.ctx, w.cancel = context.WithCancel(context.Background()) w.ctx, w.cancel = context.WithCancel(context.Background())
} }
var err error /* TODO-nwaku
if w.node, err = node.New(w.options...); err != nil {
return fmt.Errorf("failed to create a go-waku node: %v", err)
}
w.goingOnline = make(chan struct{}) w.goingOnline = make(chan struct{})
if err = w.node.Start(w.ctx); err != nil {
return fmt.Errorf("failed to start go-waku node: %v", err)
}
*/ */
w.StorenodeCycle = history.NewStorenodeCycle(w.logger, newPinger(w.node)) w.StorenodeCycle = history.NewStorenodeCycle(w.logger, newPinger(w.node))
w.HistoryRetriever = history.NewHistoryRetriever(newStorenodeRequestor(w.node, w.logger), NewHistoryProcessorWrapper(w), w.logger) w.HistoryRetriever = history.NewHistoryRetriever(newStorenodeRequestor(w.node, w.logger), NewHistoryProcessorWrapper(w), w.logger)
@ -1937,6 +1900,7 @@ func (w *Waku) RelayPeersByTopic(topic string) (*types.PeerList, error) {
AllPeers: w.node.Relay().PubSub().ListPeers(topic), AllPeers: w.node.Relay().PubSub().ListPeers(topic),
}, nil }, nil
} }
*/
func (w *Waku) SubscribeToPubsubTopic(topic string, pubkey *ecdsa.PublicKey) error { func (w *Waku) SubscribeToPubsubTopic(topic string, pubkey *ecdsa.PublicKey) error {
topic = w.GetPubsubTopic(topic) topic = w.GetPubsubTopic(topic)
@ -1971,6 +1935,7 @@ func (w *Waku) RetrievePubsubTopicKey(topic string) (*ecdsa.PrivateKey, error) {
return w.protectedTopicStore.FetchPrivateKey(topic) return w.protectedTopicStore.FetchPrivateKey(topic)
} }
/* TODO-nwaku
func (w *Waku) StorePubsubTopicKey(topic string, privKey *ecdsa.PrivateKey) error { func (w *Waku) StorePubsubTopicKey(topic string, privKey *ecdsa.PrivateKey) error {
topic = w.GetPubsubTopic(topic) topic = w.GetPubsubTopic(topic)
if w.protectedTopicStore == nil { if w.protectedTopicStore == nil {
@ -2314,8 +2279,17 @@ func wakuNew(nodeKey *ecdsa.PrivateKey,
ts = timesource.Default() ts = timesource.Default()
} }
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 private key: %v", err)
}
}
nwakuCfg.NodeKey = hex.EncodeToString(crypto.FromECDSA(nodeKey)) nwakuCfg.NodeKey = hex.EncodeToString(crypto.FromECDSA(nodeKey))
nwakuCfg.TcpPort, nwakuCfg.Discv5UdpPort, err = getFreePortIfNeeded(nwakuCfg.TcpPort, nwakuCfg.Discv5UdpPort, logger)
// TODO-nwaku // TODO-nwaku
// TODO: merge Config and WakuConfig // TODO: merge Config and WakuConfig
cfg = setDefaults(cfg) cfg = setDefaults(cfg)
@ -3154,3 +3128,51 @@ func getContextTimeoutMilliseconds(ctx context.Context) int {
} }
return 0 return 0
} }
func getFreePortIfNeeded(tcpPort int, discV5UDPPort int, logger *zap.Logger) (int, int, error) {
if tcpPort == 0 {
for i := 0; i < 10; i++ {
tcpAddr, err := net.ResolveTCPAddr("tcp", net.JoinHostPort("localhost", "0"))
if err != nil {
logger.Warn("unable to resolve tcp addr: %v", zap.Error(err))
continue
}
tcpListener, err := net.ListenTCP("tcp", tcpAddr)
if err != nil {
logger.Warn("unable to listen on addr", zap.Stringer("addr", tcpAddr), zap.Error(err))
continue
}
tcpPort = tcpListener.Addr().(*net.TCPAddr).Port
tcpListener.Close()
break
}
if tcpPort == 0 {
return -1, -1, errors.New("could not obtain a free TCP port")
}
}
if discV5UDPPort == 0 {
for i := 0; i < 10; i++ {
udpAddr, err := net.ResolveUDPAddr("udp", net.JoinHostPort("localhost", "0"))
if err != nil {
logger.Warn("unable to resolve udp addr: %v", zap.Error(err))
continue
}
udpListener, err := net.ListenUDP("udp", udpAddr)
if err != nil {
logger.Warn("unable to listen on addr", zap.Stringer("addr", udpAddr), zap.Error(err))
continue
}
discV5UDPPort = udpListener.LocalAddr().(*net.UDPAddr).Port
udpListener.Close()
break
}
if discV5UDPPort == 0 {
return -1, -1, errors.New("could not obtain a free UDP port")
}
}
return tcpPort, discV5UDPPort, nil
}