2021-09-27 17:52:56 +00:00
|
|
|
package discovery
|
|
|
|
|
|
|
|
import (
|
2021-09-30 23:03:19 +00:00
|
|
|
"context"
|
2021-09-27 17:52:56 +00:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/p2p/dnsdisc"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p/enode"
|
|
|
|
"github.com/libp2p/go-libp2p-core/peer"
|
2021-09-27 18:16:06 +00:00
|
|
|
|
|
|
|
ma "github.com/multiformats/go-multiaddr"
|
2021-09-27 17:52:56 +00:00
|
|
|
)
|
|
|
|
|
2021-09-30 23:03:19 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-27 17:52:56 +00:00
|
|
|
// RetrieveNodes returns a list of multiaddress given a url to a DNS discoverable
|
|
|
|
// ENR tree
|
2021-09-30 23:03:19 +00:00
|
|
|
func RetrieveNodes(ctx context.Context, url string, opts ...DnsDiscoveryOption) ([]ma.Multiaddr, error) {
|
2021-09-27 18:16:06 +00:00
|
|
|
var multiAddrs []ma.Multiaddr
|
2021-09-27 17:52:56 +00:00
|
|
|
|
2021-09-30 23:03:19 +00:00
|
|
|
params := new(DnsDiscoveryParameters)
|
|
|
|
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() {
|
2021-09-30 23:03:19 +00:00
|
|
|
m, err := EnodeToMultiAddr(node)
|
2021-09-27 17:52:56 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
multiAddrs = append(multiAddrs, m)
|
|
|
|
}
|
|
|
|
|
|
|
|
return multiAddrs, nil
|
|
|
|
}
|
|
|
|
|
2021-09-30 23:03:19 +00:00
|
|
|
func EnodeToMultiAddr(node *enode.Node) (ma.Multiaddr, error) {
|
2021-09-27 17:52:56 +00:00
|
|
|
peerID, err := peer.IDFromPublicKey(&ECDSAPublicKey{node.Pubkey()})
|
|
|
|
if err != nil {
|
2021-09-27 18:16:06 +00:00
|
|
|
return nil, err
|
2021-09-27 17:52:56 +00:00
|
|
|
}
|
|
|
|
|
2021-09-27 18:16:06 +00:00
|
|
|
return ma.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", node.IP(), node.TCP(), peerID))
|
2021-09-27 17:52:56 +00:00
|
|
|
}
|