go-libp2p-pubsub/blacklist.go

65 lines
1.3 KiB
Go
Raw Normal View History

2019-01-17 12:05:04 +00:00
package pubsub
import (
2020-02-05 08:43:21 +00:00
"sync"
"time"
2019-05-26 16:19:03 +00:00
"github.com/libp2p/go-libp2p-core/peer"
"github.com/whyrusleeping/timecache"
2019-01-17 12:05:04 +00:00
)
// Blacklist is an interface for peer blacklisting.
type Blacklist interface {
Add(peer.ID) bool
2019-01-17 12:05:04 +00:00
Contains(peer.ID) bool
}
// MapBlacklist is a blacklist implementation using a perfect map
type MapBlacklist map[peer.ID]struct{}
// NewMapBlacklist creates a new MapBlacklist
func NewMapBlacklist() Blacklist {
return MapBlacklist(make(map[peer.ID]struct{}))
}
func (b MapBlacklist) Add(p peer.ID) bool {
2019-01-17 12:05:04 +00:00
b[p] = struct{}{}
return true
2019-01-17 12:05:04 +00:00
}
func (b MapBlacklist) Contains(p peer.ID) bool {
_, ok := b[p]
return ok
}
2019-01-17 12:20:34 +00:00
// TimeCachedBlacklist is a blacklist implementation using a time cache
type TimeCachedBlacklist struct {
2020-02-05 08:43:21 +00:00
sync.RWMutex
tc *timecache.TimeCache
2019-01-17 12:20:34 +00:00
}
// NewTimeCachedBlacklist creates a new TimeCachedBlacklist with the given expiry duration
func NewTimeCachedBlacklist(expiry time.Duration) (Blacklist, error) {
2020-02-05 08:43:21 +00:00
b := &TimeCachedBlacklist{tc: timecache.NewTimeCache(expiry)}
2019-01-17 12:20:34 +00:00
return b, nil
}
// Add returns a bool saying whether Add of peer was successful
func (b *TimeCachedBlacklist) Add(p peer.ID) bool {
2020-02-05 08:43:21 +00:00
b.Lock()
2020-02-05 09:03:20 +00:00
defer b.Unlock()
s := p.String()
if b.tc.Has(s) {
return false
}
b.tc.Add(s)
return true
2019-01-17 12:20:34 +00:00
}
2020-02-05 08:43:21 +00:00
func (b *TimeCachedBlacklist) Contains(p peer.ID) bool {
b.RLock()
defer b.RUnlock()
return b.tc.Has(p.String())
2019-01-17 12:20:34 +00:00
}