github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/p2p/security/security.go (about) 1 package security 2 3 import ( 4 log "github.com/sirupsen/logrus" 5 6 cfg "github.com/bytom/bytom/config" 7 ) 8 9 const logModule = "p2pSecurity" 10 11 type Security struct { 12 filter *PeerFilter 13 blacklist *Blacklist 14 peersBanScore *PeersBanScore 15 } 16 17 func NewSecurity(config *cfg.Config) *Security { 18 return &Security{ 19 filter: NewPeerFilter(), 20 blacklist: NewBlacklist(config), 21 peersBanScore: NewPeersScore(), 22 } 23 } 24 25 func (s *Security) DoFilter(ip string, pubKey string) error { 26 return s.filter.doFilter(ip, pubKey) 27 } 28 29 func (s *Security) IsBanned(ip string, level byte, reason string) bool { 30 if ok := s.peersBanScore.Increase(ip, level, reason); !ok { 31 return false 32 } 33 34 if err := s.blacklist.AddPeer(ip); err != nil { 35 log.WithFields(log.Fields{"module": logModule, "err": err}).Error("fail on add ban peer") 36 } 37 //clear peer score 38 s.peersBanScore.DelPeer(ip) 39 return true 40 } 41 42 func (s *Security) RegisterFilter(filter Filter) { 43 s.filter.register(filter) 44 } 45 46 func (s *Security) Start() error { 47 if err := s.blacklist.LoadPeers(); err != nil { 48 return err 49 } 50 51 s.filter.register(s.blacklist) 52 return nil 53 }