discovery implementation using ContentRouting

This commit is contained in:
vyzo 2018-10-12 14:56:09 +03:00
commit d0766bb0ac
1 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,64 @@
package discovery
import (
"context"
"time"
cid "github.com/ipfs/go-cid"
pstore "github.com/libp2p/go-libp2p-peerstore"
routing "github.com/libp2p/go-libp2p-routing"
mh "github.com/multiformats/go-multihash"
)
// RoutingDiscovery is an implementation of discovery using ContentRouting
type RoutingDiscovery struct {
router routing.ContentRouting
}
func NewRoutingDiscovery(router routing.ContentRouting) Discovery {
return &RoutingDiscovery{router}
}
func (d *RoutingDiscovery) Advertise(ctx context.Context, ns string, opts ...Option) (time.Duration, error) {
cid, err := nsToCid(ns)
if err != nil {
return 0, err
}
err = d.router.Provide(ctx, cid, true)
if err != nil {
return 0, err
}
// this is the dht provide validity
return 24 * time.Hour, nil
}
func (d *RoutingDiscovery) FindPeers(ctx context.Context, ns string, opts ...Option) (<-chan pstore.PeerInfo, error) {
options := &Options{}
err := options.Apply(opts...)
if err != nil {
return nil, err
}
limit := options.Limit
if limit == 0 {
limit = 100 // that's just arbitrary, but FindProvidersAsync needs a count
}
cid, err := nsToCid(ns)
if err != nil {
return nil, err
}
return d.router.FindProvidersAsync(ctx, cid, limit), nil
}
func nsToCid(ns string) (cid.Cid, error) {
h, err := mh.Encode([]byte(ns), mh.SHA2_256)
if err != nil {
return cid.Undef, err
}
return cid.NewCidV1(cid.Raw, h), nil
}