forked from libp2p/go-libp2p-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
blacklist.go
58 lines (46 loc) · 1.28 KB
/
blacklist.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package pubsub
import (
"time"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/libp2p/go-libp2p-pubsub/timecache"
)
// Blacklist is an interface for peer blacklisting.
type Blacklist interface {
Add(peer.ID) bool
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 {
b[p] = struct{}{}
return true
}
func (b MapBlacklist) Contains(p peer.ID) bool {
_, ok := b[p]
return ok
}
// TimeCachedBlacklist is a blacklist implementation using a time cache
type TimeCachedBlacklist struct {
tc timecache.TimeCache
}
// NewTimeCachedBlacklist creates a new TimeCachedBlacklist with the given expiry duration
func NewTimeCachedBlacklist(expiry time.Duration) (Blacklist, error) {
b := &TimeCachedBlacklist{tc: timecache.NewTimeCache(expiry)}
return b, nil
}
// Add returns a bool saying whether Add of peer was successful
func (b *TimeCachedBlacklist) Add(p peer.ID) bool {
s := p.String()
if b.tc.Has(s) {
return false
}
b.tc.Add(s)
return true
}
func (b *TimeCachedBlacklist) Contains(p peer.ID) bool {
return b.tc.Has(p.String())
}