Documentation ¶
Index ¶
- Constants
- func DefaultDecayFunction() netcache.PreprocessorFunc
- func DefaultTopicScoreParams() *pubsub.TopicScoreParams
- func GeometricDecay(score float64, decay float64, lastUpdated time.Time) (float64, error)
- func HasValidFlowIdentity(idProvider module.IdentityProvider, pid peer.ID) (*flow.Identity, error)
- func InitAppScoreRecordState() p2p.GossipSubSpamRecord
- func IsInvalidPeerIDError(this error) bool
- func NewInvalidPeerIDError(peerId peer.ID, status peerIdStatus) error
- type GossipSubAppSpecificScoreRegistry
- type GossipSubAppSpecificScoreRegistryConfig
- type GossipSubCtrlMsgPenaltyValue
- type InvalidPeerIDError
- type ScoreOption
- type ScoreOptionConfig
- func (c *ScoreOptionConfig) OverrideAppSpecificScoreFunction(appSpecificScoreFunction func(peer.ID) float64)
- func (c *ScoreOptionConfig) OverrideDecayInterval(interval time.Duration)
- func (c *ScoreOptionConfig) OverrideTopicScoreParams(topic channels.Topic, topicScoreParams *pubsub.TopicScoreParams)
- func (c *ScoreOptionConfig) SetCacheMetrics(metrics module.HeroCacheMetrics)
- func (c *ScoreOptionConfig) SetCacheSize(size uint32)
- func (c *ScoreOptionConfig) SetRegisterNotificationConsumerFunc(f func(p2p.GossipSubInvCtrlMsgNotifConsumer))
- type SubscriptionProvider
- type SubscriptionValidator
Constants ¶
const ( // PeerIdStatusUnknown indicates that the peer id is unknown. PeerIdStatusUnknown peerIdStatus = "unknown identity" // PeerIdStatusEjected indicates that the peer id belongs to an identity that has been ejected. PeerIdStatusEjected peerIdStatus = "ejected identity" )
const ( // DefaultAppSpecificScoreWeight is the default weight for app-specific scores. It is used to scale the app-specific // scores to the same range as the other scores. At the current version, we don't distinguish between the app-specific // scores and the other scores, so we set it to 1. DefaultAppSpecificScoreWeight = 1 // MaxAppSpecificReward is the default reward for well-behaving staked peers. If a peer does not have // any misbehavior record, e.g., invalid subscription, invalid message, etc., it will be rewarded with this score. MaxAppSpecificReward = float64(100) // MaxAppSpecificPenalty is the maximum penalty for sever offenses that we apply to a remote node score. The score // mechanism of GossipSub in Flow is designed in a way that all other infractions are penalized with a fraction of // this value. We have also set the other parameters such as DefaultGraylistThreshold, DefaultGossipThreshold and DefaultPublishThreshold to // be a bit higher than this, i.e., MaxAppSpecificPenalty + 1. This ensures that a node with a score of MaxAppSpecificPenalty // will be graylisted (i.e., all incoming and outgoing RPCs are rejected) and will not be able to publish or gossip any messages. MaxAppSpecificPenalty = -1 * MaxAppSpecificReward MinAppSpecificPenalty = -1 // DefaultStakedIdentityReward is the default reward for staking peers. It is applied to the peer's score when // the peer does not have any misbehavior record, e.g., invalid subscription, invalid message, etc. // The purpose is to reward the staking peers for their contribution to the network and prioritize them in neighbor selection. DefaultStakedIdentityReward = MaxAppSpecificReward // DefaultUnknownIdentityPenalty is the default penalty for unknown identity. It is applied to the peer's score when // the peer is not in the identity list. DefaultUnknownIdentityPenalty = MaxAppSpecificPenalty // DefaultInvalidSubscriptionPenalty is the default penalty for invalid subscription. It is applied to the peer's score when // the peer subscribes to a topic that it is not authorized to subscribe to. DefaultInvalidSubscriptionPenalty = MaxAppSpecificPenalty // DefaultGossipThreshold when a peer's penalty drops below this threshold, // no gossip is emitted towards that peer and gossip from that peer is ignored. // // Validation Constraint: GossipThreshold >= PublishThreshold && GossipThreshold < 0 // // How we use it: // As current max penalty is -100, we set the threshold to -99 so that all gossips // to and from peers with penalty -100 are ignored. DefaultGossipThreshold = MaxAppSpecificPenalty + 1 // DefaultPublishThreshold when a peer's penalty drops below this threshold, // self-published messages are not propagated towards this peer. // // Validation Constraint: // PublishThreshold >= GraylistThreshold && PublishThreshold <= GossipThreshold && PublishThreshold < 0. // // How we use it: // As current max penalty is -100, we set the threshold to -99 so that all penalized peers are deprived of // receiving any published messages. DefaultPublishThreshold = MaxAppSpecificPenalty + 1 // DefaultGraylistThreshold when a peer's penalty drops below this threshold, the peer is graylisted, i.e., // incoming RPCs from the peer are ignored. // // Validation Constraint: // GraylistThreshold =< PublishThreshold && GraylistThreshold =< GossipThreshold && GraylistThreshold < 0 // // How we use it: // As current max penalty is -100, we set the threshold to -99 so that all penalized peers are graylisted. DefaultGraylistThreshold = MaxAppSpecificPenalty + 1 // DefaultAcceptPXThreshold when a peer sends us PX information with a prune, we only accept it and connect to the supplied // peers if the originating peer's penalty exceeds this threshold. // // Validation Constraint: must be non-negative. // // How we use it: // As current max reward is 100, we set the threshold to 99 so that we only receive supplied peers from // well-behaved peers. DefaultAcceptPXThreshold = MaxAppSpecificReward - 1 // DefaultOpportunisticGraftThreshold when the median peer penalty in the mesh drops below this value, // the peer may select more peers with penalty above the median to opportunistically graft on the mesh. // // Validation Constraint: must be non-negative. // // How we use it: // We set it to the MaxAppSpecificReward + 1 so that we only opportunistically graft peers that are not access nodes (i.e., with MinAppSpecificPenalty), // or penalized peers (i.e., with MaxAppSpecificPenalty). DefaultOpportunisticGraftThreshold = MaxAppSpecificReward + 1 // MaxDebugLogs sets the max number of debug/trace log events per second. Logs emitted above // this threshold are dropped. MaxDebugLogs = 50 )
Variables ¶
This section is empty.
Functions ¶
func DefaultDecayFunction ¶ added in v0.31.0
func DefaultDecayFunction() netcache.PreprocessorFunc
DefaultDecayFunction is the default decay function that is used to decay the application specific penalty of a peer. It is used if no decay function is provided in the configuration. It decays the application specific penalty of a peer if it is negative.
func DefaultTopicScoreParams ¶ added in v0.32.0
func DefaultTopicScoreParams() *pubsub.TopicScoreParams
DefaultTopicScoreParams returns the default score params for topics.
func GeometricDecay ¶ added in v0.31.0
GeometricDecay returns the decayed score based on the decay factor and the time since the last update.
The decayed score is calculated as follows: penalty = score * decay^t where t is the time since the last update in seconds. Args: - score: the score to be decayed. - decay: the decay factor, it should be in the range of (0, 1]. - lastUpdated: the time when the penalty was last updated. Returns:
- the decayed score.
- an error if the decay factor is not in the range of (0, 1] or the decayed score is NaN. it also returns an error if the last updated time is in the future (to avoid overflow). The error is considered irrecoverable (unless the parameters can be adjusted).
func HasValidFlowIdentity ¶ added in v0.28.1
HasValidFlowIdentity checks if the peer has a valid Flow identity.
func InitAppScoreRecordState ¶ added in v0.31.0
func InitAppScoreRecordState() p2p.GossipSubSpamRecord
InitAppScoreRecordState initializes the gossipsub spam record state for a peer. Returns:
- a gossipsub spam record with the default decay value and 0 penalty.
func IsInvalidPeerIDError ¶
func NewInvalidPeerIDError ¶
Types ¶
type GossipSubAppSpecificScoreRegistry ¶ added in v0.31.0
type GossipSubAppSpecificScoreRegistry struct {
// contains filtered or unexported fields
}
GossipSubAppSpecificScoreRegistry is the registry for the application specific score of peers in the GossipSub protocol. The application specific score is part of the overall score of a peer, and is used to determine the peer's score based on its behavior related to the application (Flow protocol). This registry holds the view of the local peer of the application specific score of other peers in the network based on what it has observed from the network. Similar to the GossipSub score, the application specific score is meant to be private to the local peer, and is not shared with other peers in the network.
func NewGossipSubAppSpecificScoreRegistry ¶ added in v0.31.0
func NewGossipSubAppSpecificScoreRegistry(config *GossipSubAppSpecificScoreRegistryConfig) *GossipSubAppSpecificScoreRegistry
NewGossipSubAppSpecificScoreRegistry returns a new GossipSubAppSpecificScoreRegistry. Args:
config: the configuration for the registry.
Returns:
a new GossipSubAppSpecificScoreRegistry.
func (*GossipSubAppSpecificScoreRegistry) AppSpecificScoreFunc ¶ added in v0.31.0
func (r *GossipSubAppSpecificScoreRegistry) AppSpecificScoreFunc() func(peer.ID) float64
AppSpecificScoreFunc returns the application specific penalty function that is called by the GossipSub protocol to determine the application specific penalty of a peer.
func (*GossipSubAppSpecificScoreRegistry) OnInvalidControlMessageNotification ¶ added in v0.31.0
func (r *GossipSubAppSpecificScoreRegistry) OnInvalidControlMessageNotification(notification *p2p.InvCtrlMsgNotif)
OnInvalidControlMessageNotification is called when a new invalid control message notification is distributed. Any error on consuming event must handle internally. The implementation must be concurrency safe, but can be blocking.
type GossipSubAppSpecificScoreRegistryConfig ¶ added in v0.31.0
type GossipSubAppSpecificScoreRegistryConfig struct { Logger zerolog.Logger // Validator is the subscription validator used to validate the subscriptions of peers, and determine if a peer is // authorized to subscribe to a topic. Validator p2p.SubscriptionValidator // Penalty encapsulates the penalty unit for each control message type misbehaviour. Penalty GossipSubCtrlMsgPenaltyValue // IdProvider is the identity provider used to translate peer ids at the networking layer to Flow identifiers (if // an authorized peer is found). IdProvider module.IdentityProvider // Init is a factory function that returns a new GossipSubSpamRecord. It is used to initialize the spam record of // a peer when the peer is first observed by the local peer. Init func() p2p.GossipSubSpamRecord // CacheFactory is a factory function that returns a new GossipSubSpamRecordCache. It is used to initialize the spamScoreCache. // The cache is used to store the application specific penalty of peers. CacheFactory func() p2p.GossipSubSpamRecordCache }
GossipSubAppSpecificScoreRegistryConfig is the configuration for the GossipSubAppSpecificScoreRegistry. The configuration is used to initialize the registry.
type GossipSubCtrlMsgPenaltyValue ¶ added in v0.31.0
type GossipSubCtrlMsgPenaltyValue struct { Graft float64 // penalty value for an individual graft message misbehaviour. Prune float64 // penalty value for an individual prune message misbehaviour. IHave float64 // penalty value for an individual iHave message misbehaviour. IWant float64 // penalty value for an individual iWant message misbehaviour. }
GossipSubCtrlMsgPenaltyValue is the penalty value for each control message type.
func DefaultGossipSubCtrlMsgPenaltyValue ¶ added in v0.31.0
func DefaultGossipSubCtrlMsgPenaltyValue() GossipSubCtrlMsgPenaltyValue
DefaultGossipSubCtrlMsgPenaltyValue returns the default penalty value for each control message type.
type InvalidPeerIDError ¶
type InvalidPeerIDError struct {
// contains filtered or unexported fields
}
InvalidPeerIDError indicates that a peer has an invalid peer id, i.e., it is not held by an authorized Flow identity.
func (InvalidPeerIDError) Error ¶
func (e InvalidPeerIDError) Error() string
type ScoreOption ¶
type ScoreOption struct {
// contains filtered or unexported fields
}
ScoreOption is a functional option for configuring the peer scoring system.
func NewScoreOption ¶
func NewScoreOption(cfg *ScoreOptionConfig) *ScoreOption
NewScoreOption creates a new penalty option with the given configuration.
func (*ScoreOption) BuildFlowPubSubScoreOption ¶
func (s *ScoreOption) BuildFlowPubSubScoreOption() (*pubsub.PeerScoreParams, *pubsub.PeerScoreThresholds)
func (*ScoreOption) SetSubscriptionProvider ¶
func (s *ScoreOption) SetSubscriptionProvider(provider *SubscriptionProvider) error
func (*ScoreOption) TopicScoreParams ¶ added in v0.32.0
func (s *ScoreOption) TopicScoreParams(topic *pubsub.Topic) *pubsub.TopicScoreParams
TopicScoreParams returns the topic score parameters for the given topic. If the topic score parameters are not set, it returns the default topic score parameters. The custom topic parameters are set at the initialization of the score option. Args: - topic: the topic for which the score parameters are requested. Returns:
- the topic score parameters for the given topic, or the default topic score parameters if the topic score parameters are not set.
type ScoreOptionConfig ¶ added in v0.31.0
type ScoreOptionConfig struct {
// contains filtered or unexported fields
}
func NewScoreOptionConfig ¶ added in v0.31.0
func NewScoreOptionConfig(logger zerolog.Logger, idProvider module.IdentityProvider) *ScoreOptionConfig
func (*ScoreOptionConfig) OverrideAppSpecificScoreFunction ¶ added in v0.32.0
func (c *ScoreOptionConfig) OverrideAppSpecificScoreFunction(appSpecificScoreFunction func(peer.ID) float64)
OverrideAppSpecificScoreFunction sets the app specific penalty function for the penalty option. It is used to calculate the app specific penalty of a peer. If the app specific penalty function is not set, the default one is used. Note that it is always safer to use the default one, unless you know what you are doing. It is safe to call this method multiple times, the last call will be used.
func (*ScoreOptionConfig) OverrideDecayInterval ¶ added in v0.32.0
func (c *ScoreOptionConfig) OverrideDecayInterval(interval time.Duration)
OverrideDecayInterval overrides the decay interval for the penalty option. It is used to override the default decay interval for the penalty option. The decay interval is the time interval that the decay values are applied and peer scores are updated. Note: It is always recommended to use the default value unless you know what you are doing. Hence, calling this method is not recommended in production. Args:
interval: the decay interval.
Returns: none
func (*ScoreOptionConfig) OverrideTopicScoreParams ¶ added in v0.32.0
func (c *ScoreOptionConfig) OverrideTopicScoreParams(topic channels.Topic, topicScoreParams *pubsub.TopicScoreParams)
OverrideTopicScoreParams overrides the topic score parameters for the given topic. It is used to override the default topic score parameters for a specific topic. If the topic score parameters are not set, the default ones will be used.
func (*ScoreOptionConfig) SetCacheMetrics ¶ added in v0.31.0
func (c *ScoreOptionConfig) SetCacheMetrics(metrics module.HeroCacheMetrics)
SetCacheMetrics sets the cache metrics collector for the penalty option. It is used to collect metrics for the app specific penalty cache. If the cache metrics collector is not set, a no-op collector will be used. It is safe to call this method multiple times, the last call will be used.
func (*ScoreOptionConfig) SetCacheSize ¶ added in v0.31.0
func (c *ScoreOptionConfig) SetCacheSize(size uint32)
SetCacheSize sets the size of the cache used to store the app specific penalty of peers. If the cache size is not set, the default value will be used. It is safe to call this method multiple times, the last call will be used.
func (*ScoreOptionConfig) SetRegisterNotificationConsumerFunc ¶ added in v0.31.0
func (c *ScoreOptionConfig) SetRegisterNotificationConsumerFunc(f func(p2p.GossipSubInvCtrlMsgNotifConsumer))
SetRegisterNotificationConsumerFunc sets the function to register the notification consumer for the penalty option. ScoreOption uses this function to register the notification consumer for the pubsub system so that it can receive notifications of invalid control messages.
type SubscriptionProvider ¶
type SubscriptionProvider struct {
// contains filtered or unexported fields
}
SubscriptionProvider provides a list of topics a peer is subscribed to.
func NewSubscriptionProvider ¶
func NewSubscriptionProvider(logger zerolog.Logger, tp p2p.TopicProvider) *SubscriptionProvider
func (*SubscriptionProvider) GetSubscribedTopics ¶
func (s *SubscriptionProvider) GetSubscribedTopics(pid peer.ID) []string
GetSubscribedTopics returns all the subscriptions of a peer within the pubsub network. Note that the current node can only see peer subscriptions to topics that it has also subscribed to e.g., if current node has subscribed to topics A and B, and peer1 has subscribed to topics A, B, and C, then GetSubscribedTopics(peer1) will return A and B. Since this node has not subscribed to topic C, it will not be able to query for other peers subscribed to topic C.
type SubscriptionValidator ¶
type SubscriptionValidator struct {
// contains filtered or unexported fields
}
SubscriptionValidator validates that a peer is subscribed to topics that it is allowed to subscribe to. It is used to penalize peers that subscribe to topics that they are not allowed to subscribe to in GossipSub.
func NewSubscriptionValidator ¶
func NewSubscriptionValidator() *SubscriptionValidator
func (*SubscriptionValidator) CheckSubscribedToAllowedTopics ¶
CheckSubscribedToAllowedTopics checks if a peer is subscribed to topics that it is allowed to subscribe to. Args:
pid: the peer ID of the peer to check role: the role of the peer to check
Returns: error: if the peer is subscribed to topics that it is not allowed to subscribe to, an InvalidSubscriptionError is returned. The error is benign, i.e., it does not indicate an illegal state in the execution of the code. We expect this error when there are malicious peers in the network. But such errors should not lead to a crash of the node.
func (*SubscriptionValidator) RegisterSubscriptionProvider ¶
func (v *SubscriptionValidator) RegisterSubscriptionProvider(provider p2p.SubscriptionProvider) error
RegisterSubscriptionProvider registers the subscription provider with the subscription validator. This follows a dependency injection pattern. Args:
provider: the subscription provider
Returns:
error: if the subscription provider is nil, an error is returned. The error is irrecoverable, i.e., it indicates an illegal state in the execution of the code. We expect this error only when there is a bug in the code. Such errors should lead to a crash of the node.