github.com/celestiaorg/celestia-node@v0.15.0-beta.1/nodebuilder/p2p/routing.go (about)

     1  package p2p
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  
     7  	"github.com/ipfs/go-datastore"
     8  	dht "github.com/libp2p/go-libp2p-kad-dht"
     9  	"github.com/libp2p/go-libp2p/core/protocol"
    10  	"github.com/libp2p/go-libp2p/core/routing"
    11  	"go.uber.org/fx"
    12  
    13  	"github.com/celestiaorg/celestia-node/nodebuilder/node"
    14  )
    15  
    16  // contentRouting constructs nil content routing,
    17  // as for our use-case existing ContentRouting mechanisms, e.g DHT, are unsuitable
    18  func contentRouting(r routing.PeerRouting) routing.ContentRouting {
    19  	return r.(*dht.IpfsDHT)
    20  }
    21  
    22  // peerRouting provides constructor for PeerRouting over DHT.
    23  // Basically, this provides a way to discover peer addresses by respecting public keys.
    24  func peerRouting(cfg Config, tp node.Type, params routingParams) (routing.PeerRouting, error) {
    25  	opts := []dht.Option{
    26  		dht.Mode(dht.ModeAuto),
    27  		dht.BootstrapPeers(params.Peers...),
    28  		dht.ProtocolPrefix(protocol.ID(fmt.Sprintf("/celestia/%s", params.Net))),
    29  		dht.Datastore(params.DataStore),
    30  		dht.RoutingTableRefreshPeriod(cfg.RoutingTableRefreshPeriod),
    31  	}
    32  
    33  	if isBootstrapper() {
    34  		opts = append(opts,
    35  			dht.BootstrapPeers(), // no bootstrappers for a bootstrapper ¯\_(ツ)_/¯
    36  		)
    37  	}
    38  
    39  	if tp == node.Bridge || tp == node.Full {
    40  		opts = append(opts,
    41  			dht.Mode(dht.ModeServer),
    42  		)
    43  	}
    44  
    45  	d, err := dht.New(params.Ctx, params.Host, opts...)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  	params.Lc.Append(fx.Hook{
    50  		OnStart: func(ctx context.Context) error {
    51  			return d.Bootstrap(ctx)
    52  		},
    53  		OnStop: func(context.Context) error {
    54  			return d.Close()
    55  		},
    56  	})
    57  	return d, nil
    58  }
    59  
    60  type routingParams struct {
    61  	fx.In
    62  
    63  	Ctx       context.Context
    64  	Net       Network
    65  	Peers     Bootstrappers
    66  	Lc        fx.Lifecycle
    67  	Host      HostBase
    68  	DataStore datastore.Batching
    69  }