github.com/ethereum-optimism/optimism@v1.7.2/op-node/p2p/gating/scoring.go (about)

     1  package gating
     2  
     3  import (
     4  	"github.com/ethereum/go-ethereum/log"
     5  	"github.com/libp2p/go-libp2p/core/network"
     6  	"github.com/libp2p/go-libp2p/core/peer"
     7  	"github.com/multiformats/go-multiaddr"
     8  )
     9  
    10  //go:generate mockery --name Scores --output mocks/ --with-expecter=true
    11  type Scores interface {
    12  	GetPeerScore(id peer.ID) (float64, error)
    13  }
    14  
    15  // ScoringConnectionGater enhances a ConnectionGater by enforcing a minimum score for peer connections
    16  type ScoringConnectionGater struct {
    17  	BlockingConnectionGater
    18  	scores   Scores
    19  	minScore float64
    20  }
    21  
    22  func AddScoring(gater BlockingConnectionGater, scores Scores, minScore float64) *ScoringConnectionGater {
    23  	return &ScoringConnectionGater{BlockingConnectionGater: gater, scores: scores, minScore: minScore}
    24  }
    25  
    26  func (g *ScoringConnectionGater) checkScore(p peer.ID) (allow bool, score float64) {
    27  	score, err := g.scores.GetPeerScore(p)
    28  	if err != nil {
    29  		return false, score
    30  	}
    31  	return score >= g.minScore, score
    32  }
    33  
    34  func (g *ScoringConnectionGater) InterceptPeerDial(p peer.ID) (allow bool) {
    35  	if !g.BlockingConnectionGater.InterceptPeerDial(p) {
    36  		return false
    37  	}
    38  	check, score := g.checkScore(p)
    39  	if !check {
    40  		log.Warn("peer has failed checkScore", "peer_id", p, "score", score, "min_score", g.minScore)
    41  	}
    42  	return check
    43  }
    44  
    45  func (g *ScoringConnectionGater) InterceptAddrDial(id peer.ID, ma multiaddr.Multiaddr) (allow bool) {
    46  	if !g.BlockingConnectionGater.InterceptAddrDial(id, ma) {
    47  		return false
    48  	}
    49  	check, score := g.checkScore(id)
    50  	if !check {
    51  		log.Warn("peer has failed checkScore", "peer_id", id, "score", score, "min_score", g.minScore)
    52  	}
    53  	return check
    54  }
    55  
    56  func (g *ScoringConnectionGater) InterceptSecured(dir network.Direction, id peer.ID, mas network.ConnMultiaddrs) (allow bool) {
    57  	if !g.BlockingConnectionGater.InterceptSecured(dir, id, mas) {
    58  		return false
    59  	}
    60  	check, score := g.checkScore(id)
    61  	if !check {
    62  		log.Warn("peer has failed checkScore", "peer_id", id, "score", score, "min_score", g.minScore)
    63  	}
    64  	return check
    65  }