github.com/MetalBlockchain/metalgo@v1.11.9/snow/engine/common/tracker/startup.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package tracker
     5  
     6  import (
     7  	"context"
     8  	"sync"
     9  
    10  	"github.com/MetalBlockchain/metalgo/ids"
    11  	"github.com/MetalBlockchain/metalgo/utils/crypto/bls"
    12  	"github.com/MetalBlockchain/metalgo/version"
    13  )
    14  
    15  var _ Startup = (*startup)(nil)
    16  
    17  type Startup interface {
    18  	Peers
    19  
    20  	ShouldStart() bool
    21  }
    22  
    23  type startup struct {
    24  	Peers
    25  
    26  	lock          sync.RWMutex
    27  	startupWeight uint64
    28  	shouldStart   bool
    29  }
    30  
    31  func NewStartup(peers Peers, startupWeight uint64) Startup {
    32  	return &startup{
    33  		Peers:         peers,
    34  		startupWeight: startupWeight,
    35  		shouldStart:   peers.ConnectedWeight() >= startupWeight,
    36  	}
    37  }
    38  
    39  func (s *startup) OnValidatorAdded(nodeID ids.NodeID, pk *bls.PublicKey, txID ids.ID, weight uint64) {
    40  	s.lock.Lock()
    41  	defer s.lock.Unlock()
    42  
    43  	s.Peers.OnValidatorAdded(nodeID, pk, txID, weight)
    44  	s.shouldStart = s.shouldStart || s.Peers.ConnectedWeight() >= s.startupWeight
    45  }
    46  
    47  func (s *startup) OnValidatorWeightChanged(nodeID ids.NodeID, oldWeight, newWeight uint64) {
    48  	s.lock.Lock()
    49  	defer s.lock.Unlock()
    50  
    51  	s.Peers.OnValidatorWeightChanged(nodeID, oldWeight, newWeight)
    52  	s.shouldStart = s.shouldStart || s.Peers.ConnectedWeight() >= s.startupWeight
    53  }
    54  
    55  func (s *startup) Connected(ctx context.Context, nodeID ids.NodeID, nodeVersion *version.Application) error {
    56  	s.lock.Lock()
    57  	defer s.lock.Unlock()
    58  
    59  	if err := s.Peers.Connected(ctx, nodeID, nodeVersion); err != nil {
    60  		return err
    61  	}
    62  
    63  	s.shouldStart = s.shouldStart || s.Peers.ConnectedWeight() >= s.startupWeight
    64  	return nil
    65  }
    66  
    67  func (s *startup) ShouldStart() bool {
    68  	s.lock.RLock()
    69  	defer s.lock.RUnlock()
    70  
    71  	return s.shouldStart
    72  }