go-waku/waku/v2/dnsdisc/enr.go

74 lines
1.6 KiB
Go
Raw Normal View History

2021-11-16 14:22:01 +00:00
package dnsdisc
import (
"context"
"github.com/ethereum/go-ethereum/p2p/dnsdisc"
2022-05-05 19:17:35 +00:00
"github.com/ethereum/go-ethereum/p2p/enode"
"github.com/ethereum/go-ethereum/p2p/enr"
2021-11-16 14:22:01 +00:00
"github.com/status-im/go-waku/waku/v2/utils"
ma "github.com/multiformats/go-multiaddr"
)
type dnsDiscoveryParameters struct {
nameserver string
}
type DnsDiscoveryOption func(*dnsDiscoveryParameters)
// WithMultiaddress is a WakuNodeOption that configures libp2p to listen on a list of multiaddresses
func WithNameserver(nameserver string) DnsDiscoveryOption {
return func(params *dnsDiscoveryParameters) {
params.nameserver = nameserver
}
}
2022-05-05 19:17:35 +00:00
type DiscoveredNode struct {
Addresses []ma.Multiaddr
ENR *enode.Node
}
// RetrieveNodes returns a list of multiaddress given a url to a DNS discoverable ENR tree
2022-05-05 19:17:35 +00:00
func RetrieveNodes(ctx context.Context, url string, opts ...DnsDiscoveryOption) ([]DiscoveredNode, error) {
var discoveredNodes []DiscoveredNode
params := new(dnsDiscoveryParameters)
for _, opt := range opts {
opt(params)
}
client := dnsdisc.NewClient(dnsdisc.Config{
Resolver: GetResolver(ctx, params.nameserver),
})
tree, err := client.SyncTree(url)
if err != nil {
return nil, err
}
for _, node := range tree.Nodes() {
m, err := utils.Multiaddress(node)
if err != nil {
return nil, err
}
2022-05-05 19:17:35 +00:00
d := DiscoveredNode{Addresses: m}
if hasUDP(node) {
d.ENR = node
}
discoveredNodes = append(discoveredNodes, d)
}
2022-05-05 19:17:35 +00:00
return discoveredNodes, nil
}
func hasUDP(node *enode.Node) bool {
enrUDP := new(enr.UDP)
if err := node.Record().Load(enr.WithEntry(enrUDP.ENRKey(), enrUDP)); err != nil {
return err == nil
}
return false
}