github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/p2p/discover/dht/dns_seeds.go (about)

     1  package dht
     2  
     3  import (
     4  	"net"
     5  	"time"
     6  
     7  	log "github.com/sirupsen/logrus"
     8  
     9  	"github.com/bytom/bytom/consensus"
    10  	"github.com/bytom/bytom/errors"
    11  )
    12  
    13  var (
    14  	errInvalidIP     = errors.New("invalid ip address")
    15  	errDNSTimeout    = errors.New("get dns seed timeout")
    16  	errDNSSeedsEmpty = errors.New("dns seeds is empty")
    17  
    18  	dnsTimeout = 5 * time.Second
    19  )
    20  
    21  // QueryDNSSeeds Query the DNS seeds.
    22  func QueryDNSSeeds(lookupHost func(host string) (addrs []string, err error)) ([]string, error) {
    23  	if len(consensus.ActiveNetParams.DNSSeeds) == 0 {
    24  		return nil, errDNSSeedsEmpty
    25  	}
    26  
    27  	resultCh := make(chan *[]string, 1)
    28  	for _, dnsSeed := range consensus.ActiveNetParams.DNSSeeds {
    29  		go queryDNSSeeds(lookupHost, resultCh, dnsSeed, consensus.ActiveNetParams.DefaultPort)
    30  	}
    31  
    32  	select {
    33  	case result := <-resultCh:
    34  		return *result, nil
    35  	case <-time.After(dnsTimeout):
    36  		return nil, errDNSTimeout
    37  	}
    38  }
    39  
    40  func queryDNSSeeds(lookupHost func(host string) (addrs []string, err error), resultCh chan *[]string, dnsSeed, port string) {
    41  	var seeds []string
    42  
    43  	//TODO add proxy
    44  	addrs, err := lookupHost(dnsSeed)
    45  	if err != nil {
    46  		log.WithFields(log.Fields{"module": logModule, "err": err, "dnsSeed": dnsSeed}).Error("fail on look up host")
    47  		return
    48  	}
    49  
    50  	for _, addr := range addrs {
    51  		if ip := net.ParseIP(addr); ip == nil {
    52  			log.WithFields(log.Fields{"module": logModule, "err": errInvalidIP, "dnsSeed": dnsSeed}).Error("fail on parse IP")
    53  			return
    54  		}
    55  
    56  		seeds = append(seeds, net.JoinHostPort(addr, port))
    57  	}
    58  	if len(seeds) == 0 {
    59  		return
    60  	}
    61  	//if channel is full, drop it
    62  	select {
    63  	case resultCh <- &seeds:
    64  	default:
    65  	}
    66  }