2018-12-05 13:57:05 +00:00
|
|
|
package mailservers
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/p2p"
|
|
|
|
"github.com/ethereum/go-ethereum/p2p/enode"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
// ErrNoConnected returned when mail servers are not connected.
|
|
|
|
ErrNoConnected = errors.New("no connected mail servers")
|
|
|
|
)
|
|
|
|
|
|
|
|
// PeersProvider is an interface for requesting list of peers.
|
|
|
|
type PeersProvider interface {
|
|
|
|
Peers() []*p2p.Peer
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewPeerStore returns an instance of PeerStore.
|
2018-12-12 09:39:00 +00:00
|
|
|
func NewPeerStore(cache *Cache) *PeerStore {
|
|
|
|
return &PeerStore{
|
|
|
|
nodes: map[enode.ID]*enode.Node{},
|
|
|
|
cache: cache,
|
|
|
|
}
|
2018-12-05 13:57:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// PeerStore stores list of selected mail servers and keeps N of them connected.
|
|
|
|
type PeerStore struct {
|
|
|
|
mu sync.RWMutex
|
|
|
|
nodes map[enode.ID]*enode.Node
|
2018-12-12 09:39:00 +00:00
|
|
|
|
|
|
|
cache *Cache
|
2018-12-05 13:57:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Exist confirms that peers was added to a store.
|
2018-12-12 09:39:00 +00:00
|
|
|
func (ps *PeerStore) Exist(nodeID enode.ID) bool {
|
2018-12-05 13:57:05 +00:00
|
|
|
ps.mu.RLock()
|
|
|
|
defer ps.mu.RUnlock()
|
2018-12-12 09:39:00 +00:00
|
|
|
_, exist := ps.nodes[nodeID]
|
2018-12-05 13:57:05 +00:00
|
|
|
return exist
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns instance of the node with requested ID or nil if ID is not found.
|
2018-12-12 09:39:00 +00:00
|
|
|
func (ps *PeerStore) Get(nodeID enode.ID) *enode.Node {
|
2018-12-05 13:57:05 +00:00
|
|
|
ps.mu.RLock()
|
|
|
|
defer ps.mu.RUnlock()
|
2018-12-12 09:39:00 +00:00
|
|
|
return ps.nodes[nodeID]
|
2018-12-05 13:57:05 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// Update updates peers locally.
|
2018-12-12 09:39:00 +00:00
|
|
|
func (ps *PeerStore) Update(nodes []*enode.Node) error {
|
2018-12-05 13:57:05 +00:00
|
|
|
ps.mu.Lock()
|
|
|
|
ps.nodes = map[enode.ID]*enode.Node{}
|
|
|
|
for _, n := range nodes {
|
|
|
|
ps.nodes[n.ID()] = n
|
|
|
|
}
|
2018-12-12 09:39:00 +00:00
|
|
|
ps.mu.Unlock()
|
|
|
|
return ps.cache.Replace(nodes)
|
2018-12-05 13:57:05 +00:00
|
|
|
}
|