github.com/ava-labs/avalanchego@v1.11.11/genesis/bootstrappers.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package genesis
     5  
     6  import (
     7  	"encoding/json"
     8  	"fmt"
     9  	"net/netip"
    10  
    11  	_ "embed"
    12  
    13  	"github.com/ava-labs/avalanchego/ids"
    14  	"github.com/ava-labs/avalanchego/utils/constants"
    15  	"github.com/ava-labs/avalanchego/utils/sampler"
    16  )
    17  
    18  var (
    19  	//go:embed bootstrappers.json
    20  	bootstrappersPerNetworkJSON []byte
    21  
    22  	bootstrappersPerNetwork map[string][]Bootstrapper
    23  )
    24  
    25  func init() {
    26  	if err := json.Unmarshal(bootstrappersPerNetworkJSON, &bootstrappersPerNetwork); err != nil {
    27  		panic(fmt.Sprintf("failed to decode bootstrappers.json %v", err))
    28  	}
    29  }
    30  
    31  // Represents the relationship between the nodeID and the nodeIP.
    32  // The bootstrapper is sometimes called "anchor" or "beacon" node.
    33  type Bootstrapper struct {
    34  	ID ids.NodeID     `json:"id"`
    35  	IP netip.AddrPort `json:"ip"`
    36  }
    37  
    38  // GetBootstrappers returns all default bootstrappers for the provided network.
    39  func GetBootstrappers(networkID uint32) []Bootstrapper {
    40  	networkName := constants.NetworkIDToNetworkName[networkID]
    41  	return bootstrappersPerNetwork[networkName]
    42  }
    43  
    44  // SampleBootstrappers returns the some beacons this node should connect to
    45  func SampleBootstrappers(networkID uint32, count int) []Bootstrapper {
    46  	bootstrappers := GetBootstrappers(networkID)
    47  	count = min(count, len(bootstrappers))
    48  
    49  	s := sampler.NewUniform()
    50  	s.Initialize(uint64(len(bootstrappers)))
    51  	indices, _ := s.Sample(count)
    52  
    53  	sampled := make([]Bootstrapper, 0, len(indices))
    54  	for _, index := range indices {
    55  		sampled = append(sampled, bootstrappers[int(index)])
    56  	}
    57  	return sampled
    58  }