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