status-go/vendor/github.com/libp2p/go-libp2p-peerstore/peerstore.go

92 lines
1.8 KiB
Go
Raw Normal View History

package peerstore
import (
"fmt"
2019-06-09 07:24:20 +00:00
"io"
2019-06-09 07:24:20 +00:00
peer "github.com/libp2p/go-libp2p-peer"
)
2019-06-09 07:24:20 +00:00
var _ Peerstore = (*peerstore)(nil)
2019-06-09 07:24:20 +00:00
type peerstore struct {
Metrics
2019-06-09 07:24:20 +00:00
KeyBook
AddrBook
ProtoBook
PeerMetadata
}
2019-06-09 07:24:20 +00:00
// NewPeerstore creates a data structure that stores peer data, backed by the
// supplied implementations of KeyBook, AddrBook and PeerMetadata.
func NewPeerstore(kb KeyBook, ab AddrBook, pb ProtoBook, md PeerMetadata) Peerstore {
return &peerstore{
KeyBook: kb,
AddrBook: ab,
ProtoBook: pb,
PeerMetadata: md,
Metrics: NewMetrics(),
}
}
2019-06-09 07:24:20 +00:00
func (ps *peerstore) Close() (err error) {
var errs []error
weakClose := func(name string, c interface{}) {
if cl, ok := c.(io.Closer); ok {
if err = cl.Close(); err != nil {
errs = append(errs, fmt.Errorf("%s error: %s", name, err))
}
}
}
2019-06-09 07:24:20 +00:00
weakClose("keybook", ps.KeyBook)
weakClose("addressbook", ps.AddrBook)
weakClose("protobook", ps.ProtoBook)
weakClose("peermetadata", ps.PeerMetadata)
2019-06-09 07:24:20 +00:00
if len(errs) > 0 {
return fmt.Errorf("failed while closing peerstore; err(s): %q", errs)
}
return nil
}
2019-06-09 07:24:20 +00:00
func (ps *peerstore) Peers() peer.IDSlice {
set := map[peer.ID]struct{}{}
2019-06-09 07:24:20 +00:00
for _, p := range ps.PeersWithKeys() {
set[p] = struct{}{}
}
2019-06-09 07:24:20 +00:00
for _, p := range ps.PeersWithAddrs() {
set[p] = struct{}{}
}
2019-06-09 07:24:20 +00:00
pps := make(peer.IDSlice, 0, len(set))
for p := range set {
pps = append(pps, p)
}
return pps
}
func (ps *peerstore) PeerInfo(p peer.ID) PeerInfo {
return PeerInfo{
ID: p,
2019-06-09 07:24:20 +00:00
Addrs: ps.AddrBook.Addrs(p),
}
}
2019-06-09 07:24:20 +00:00
func PeerInfos(ps Peerstore, peers peer.IDSlice) []PeerInfo {
pi := make([]PeerInfo, len(peers))
for i, p := range peers {
pi[i] = ps.PeerInfo(p)
}
return pi
}
2019-06-09 07:24:20 +00:00
func PeerInfoIDs(pis []PeerInfo) peer.IDSlice {
ps := make(peer.IDSlice, len(pis))
for i, pi := range pis {
ps[i] = pi.ID
}
return ps
}