github.com/koko1123/flow-go-1@v0.29.6/network/p2p/dht/dht.go (about)

     1  package dht
     2  
     3  import (
     4  	"context"
     5  
     6  	dht "github.com/libp2p/go-libp2p-kad-dht"
     7  	"github.com/libp2p/go-libp2p/core/host"
     8  	"github.com/libp2p/go-libp2p/core/peer"
     9  	"github.com/libp2p/go-libp2p/core/protocol"
    10  	"github.com/rs/zerolog"
    11  
    12  	"github.com/koko1123/flow-go-1/module"
    13  )
    14  
    15  // This produces a new IPFS DHT
    16  // on the name, see https://github.com/libp2p/go-libp2p-kad-dht/issues/337
    17  func NewDHT(ctx context.Context, host host.Host, prefix protocol.ID, logger zerolog.Logger, metrics module.DHTMetrics, options ...dht.Option) (*dht.IpfsDHT, error) {
    18  	allOptions := append(options, dht.ProtocolPrefix(prefix))
    19  
    20  	kdht, err := dht.New(ctx, host, allOptions...)
    21  	if err != nil {
    22  		return nil, err
    23  	}
    24  
    25  	if err = kdht.Bootstrap(ctx); err != nil {
    26  		return nil, err
    27  	}
    28  
    29  	dhtLogger := logger.With().Str("component", "dht").Logger()
    30  
    31  	routingTable := kdht.RoutingTable()
    32  	peerRemovedCb := routingTable.PeerRemoved
    33  	peerAddedCb := routingTable.PeerAdded
    34  	routingTable.PeerRemoved = func(pid peer.ID) {
    35  		peerRemovedCb(pid)
    36  		dhtLogger.Debug().Str("peer_id", pid.String()).Msg("peer removed from routing table")
    37  		metrics.RoutingTablePeerRemoved()
    38  	}
    39  	routingTable.PeerAdded = func(pid peer.ID) {
    40  		peerAddedCb(pid)
    41  		dhtLogger.Debug().Str("peer_id", pid.String()).Msg("peer added to routing table")
    42  		metrics.RoutingTablePeerAdded()
    43  	}
    44  
    45  	return kdht, nil
    46  }
    47  
    48  // DHT defaults to ModeAuto which will automatically switch the DHT between Server and Client modes based on
    49  // whether the node appears to be publicly reachable (e.g. not behind a NAT and with a public IP address).
    50  // This default tends to make test setups fail (since the test nodes are normally not reachable by the public
    51  // network), but is useful for improving the stability and performance of live public networks.
    52  // While we could force all nodes to be DHT Servers, a bunch of nodes otherwise not reachable by most of the
    53  // network => network partition
    54  
    55  func AsServer() dht.Option {
    56  	return dht.Mode(dht.ModeServer)
    57  }
    58  
    59  func AsClient() dht.Option {
    60  	return dht.Mode(dht.ModeClient)
    61  }