2021-11-16 14:22:01 +00:00
|
|
|
package dnsdisc
|
2021-09-27 17:52:56 +00:00
|
|
|
|
|
|
|
import (
|
2021-09-30 23:03:19 +00:00
|
|
|
"context"
|
2021-09-27 17:52:56 +00:00
|
|
|
|
|
|
|
"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"
|
2021-09-27 18:16:06 +00:00
|
|
|
|
|
|
|
ma "github.com/multiformats/go-multiaddr"
|
2021-09-27 17:52:56 +00:00
|
|
|
)
|
|
|
|
|
2022-04-25 19:31:26 +00:00
|
|
|
type dnsDiscoveryParameters struct {
|
2021-09-30 23:03:19 +00:00
|
|
|
nameserver string
|
|
|
|
}
|
|
|
|
|
2022-04-25 19:31:26 +00:00
|
|
|
type DnsDiscoveryOption func(*dnsDiscoveryParameters)
|
2021-09-30 23:03:19 +00:00
|
|
|
|
2022-07-25 15:28:17 +00:00
|
|
|
// WithNameserver is a DnsDiscoveryOption that configures the nameserver to use
|
2021-09-30 23:03:19 +00:00
|
|
|
func WithNameserver(nameserver string) DnsDiscoveryOption {
|
2022-04-25 19:31:26 +00:00
|
|
|
return func(params *dnsDiscoveryParameters) {
|
2021-09-30 23:03:19 +00:00
|
|
|
params.nameserver = nameserver
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-05 19:17:35 +00:00
|
|
|
type DiscoveredNode struct {
|
|
|
|
Addresses []ma.Multiaddr
|
|
|
|
ENR *enode.Node
|
|
|
|
}
|
|
|
|
|
2022-04-25 19:31:26 +00:00
|
|
|
// 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
|
2021-09-27 17:52:56 +00:00
|
|
|
|
2022-04-25 19:31:26 +00:00
|
|
|
params := new(dnsDiscoveryParameters)
|
2021-09-30 23:03:19 +00:00
|
|
|
for _, opt := range opts {
|
|
|
|
opt(params)
|
|
|
|
}
|
|
|
|
|
|
|
|
client := dnsdisc.NewClient(dnsdisc.Config{
|
|
|
|
Resolver: GetResolver(ctx, params.nameserver),
|
|
|
|
})
|
2021-09-27 17:52:56 +00:00
|
|
|
|
|
|
|
tree, err := client.SyncTree(url)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, node := range tree.Nodes() {
|
2022-04-25 19:31:26 +00:00
|
|
|
m, err := utils.Multiaddress(node)
|
2021-09-27 17:52:56 +00:00
|
|
|
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)
|
2021-09-27 17:52:56 +00:00
|
|
|
}
|
|
|
|
|
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
|
2021-09-27 17:52:56 +00:00
|
|
|
}
|