Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate peers on startup #231

Merged
merged 23 commits into from
Mar 19, 2024
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 47 additions & 28 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,10 @@ type SourceBlockchain struct {
SupportedDestinations []string `mapstructure:"supported-destinations" json:"supported-destinations"`
ProcessHistoricalBlocksFromHeight uint64 `mapstructure:"process-historical-blocks-from-height" json:"process-historical-blocks-from-height"`

// convenience field to access the supported destinations after initialization
// convenience fields to access parsed data after initialization
supportedDestinations set.Set[ids.ID]
subnetID ids.ID
blockchainID ids.ID
}

type DestinationBlockchain struct {
Expand All @@ -81,6 +83,10 @@ type DestinationBlockchain struct {

// Fetched from the chain after startup
warpQuorum WarpQuorum

// convenience fields to access parsed data after initialization
subnetID ids.ID
blockchainID ids.ID
}

type WarpQuorum struct {
Expand All @@ -97,10 +103,6 @@ type Config struct {
DestinationBlockchains []*DestinationBlockchain `mapstructure:"destination-blockchains" json:"destination-blockchains"`
ProcessMissedBlocks bool `mapstructure:"process-missed-blocks" json:"process-missed-blocks"`
ManualWarpMessages []*ManualWarpMessage `mapstructure:"manual-warp-messages" json:"manual-warp-messages"`

// convenience fields to access the source subnet and chain IDs after initialization
sourceSubnetIDs []ids.ID
sourceBlockchainIDs []ids.ID
Comment on lines -101 to -103
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These were only used to pass to the app request network constructor. With this change, it makes more sense to pass the configuration and iterate over the SourceBlockchain and DestinationBlockchain slices directly, so the parsed IDs were moved there.

}

func SetDefaultConfigValues(v *viper.Viper) {
Expand Down Expand Up @@ -208,8 +210,6 @@ func (c *Config) Validate() error {

// Validate the source chains and store the source subnet and chain IDs for future use
sourceBlockchains := set.NewSet[string](len(c.SourceBlockchains))
var sourceSubnetIDs []ids.ID
var sourceBlockchainIDs []ids.ID
for _, s := range c.SourceBlockchains {
// Validate configuration
if err := s.Validate(&destinationChains); err != nil {
Expand All @@ -220,24 +220,8 @@ func (c *Config) Validate() error {
return errors.New("configured source subnets must have unique chain IDs")
}
sourceBlockchains.Add(s.BlockchainID)

// Save IDs for future use
subnetID, err := ids.FromString(s.SubnetID)
if err != nil {
return fmt.Errorf("invalid subnetID in configuration. error: %w", err)
}
sourceSubnetIDs = append(sourceSubnetIDs, subnetID)

blockchainID, err := ids.FromString(s.BlockchainID)
if err != nil {
return fmt.Errorf("invalid subnetID in configuration. error: %w", err)
}
sourceBlockchainIDs = append(sourceBlockchainIDs, blockchainID)
}

c.sourceSubnetIDs = sourceSubnetIDs
c.sourceBlockchainIDs = sourceBlockchainIDs

// Validate the manual warp messages
for i, msg := range c.ManualWarpMessages {
if err := msg.Validate(); err != nil {
Expand Down Expand Up @@ -417,6 +401,18 @@ func (s *SourceBlockchain) Validate(destinationBlockchainIDs *set.Set[string]) e
}
}

// Validate and store the subnet and blockchain IDs for future use
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for this PR, but we should consider splitting config.go up into multiple files at some point soon. I think SourceBlockchain and DestinationBlockchain could each be put in their own file still in the config package and could help improve navigation/readability.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

agreed and some of the similarities between the source/destination can be abstracted

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

some of the similarities between the source/destination can be abstracted

Viper doesn't play nicely with this unfortunately. There may be a workaround, but I haven't looked to deeply into it.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It doesn't look too bad, but we can definitely defer to a separate ticket https://stackoverflow.com/questions/47185318/multiple-config-files-with-go-viper

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To clarify, I think we should keep a single user-facing configuration file, but split it into multiple Go files for easier code readability.

I experimented with Matt's suggestion of composing SourceBlockchain and DestinationBlockchain using a common type, but Viper seemed to have trouble unmarshalling JSON into them. Definitely worth revisiting if we decide to go for those config improvements.

blockchainID, err := ids.FromString(s.BlockchainID)
if err != nil {
return fmt.Errorf("invalid blockchainID in configuration. error: %w", err)
}
s.blockchainID = blockchainID
subnetID, err := ids.FromString(s.SubnetID)
if err != nil {
return fmt.Errorf("invalid subnetID in configuration. error: %w", err)
}
s.subnetID = subnetID

// Validate and store the allowed destinations for future use
s.supportedDestinations = set.Set[ids.ID]{}

Expand Down Expand Up @@ -447,6 +443,14 @@ func (s *SourceBlockchain) Validate(destinationBlockchainIDs *set.Set[string]) e
return nil
}

func (s *SourceBlockchain) GetSubnetID() ids.ID {
return s.subnetID
}

func (s *SourceBlockchain) GetBlockchainID() ids.ID {
return s.blockchainID
}

// Validatees the destination subnet configuration
func (s *DestinationBlockchain) Validate() error {
if _, err := ids.FromString(s.SubnetID); err != nil {
Expand All @@ -473,9 +477,29 @@ func (s *DestinationBlockchain) Validate() error {
return fmt.Errorf("unsupported VM type for source subnet: %s", s.VM)
}

// Validate and store the subnet and blockchain IDs for future use
blockchainID, err := ids.FromString(s.BlockchainID)
if err != nil {
return fmt.Errorf("invalid blockchainID in configuration. error: %w", err)
}
s.blockchainID = blockchainID
subnetID, err := ids.FromString(s.SubnetID)
if err != nil {
return fmt.Errorf("invalid subnetID in configuration. error: %w", err)
}
s.subnetID = subnetID

return nil
}

func (s *DestinationBlockchain) GetSubnetID() ids.ID {
return s.subnetID
}

func (s *DestinationBlockchain) GetBlockchainID() ids.ID {
return s.blockchainID
}

func (s *DestinationBlockchain) initializeWarpQuorum() error {
blockchainID, err := ids.FromString(s.BlockchainID)
if err != nil {
Expand Down Expand Up @@ -514,11 +538,6 @@ func (s *DestinationBlockchain) GetRelayerAccountInfo() (*ecdsa.PrivateKey, comm
// Top-level config getters
//

// GetSourceIDs returns the Subnet and Chain IDs of all subnets configured as a source
func (c *Config) GetSourceIDs() ([]ids.ID, []ids.ID) {
return c.sourceSubnetIDs, c.sourceBlockchainIDs
}

func (c *Config) GetWarpQuorum(blockchainID ids.ID) (WarpQuorum, error) {
for _, s := range c.DestinationBlockchains {
if blockchainID.String() == s.BlockchainID {
Expand Down
14 changes: 7 additions & 7 deletions database/json_file_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,30 +34,30 @@ type JSONFileStorage struct {
}

// NewJSONFileStorage creates a new JSONFileStorage instance
func NewJSONFileStorage(logger logging.Logger, dir string, networks []ids.ID) (*JSONFileStorage, error) {
func NewJSONFileStorage(logger logging.Logger, dir string, chainIDs []ids.ID) (*JSONFileStorage, error) {
cam-schultz marked this conversation as resolved.
Show resolved Hide resolved
storage := &JSONFileStorage{
dir: filepath.Clean(dir),
mutexes: make(map[ids.ID]*sync.RWMutex),
logger: logger,
currentState: make(map[ids.ID]chainState),
}

for _, network := range networks {
storage.currentState[network] = make(chainState)
storage.mutexes[network] = &sync.RWMutex{}
for _, chainID := range chainIDs {
storage.currentState[chainID] = make(chainState)
storage.mutexes[chainID] = &sync.RWMutex{}
cam-schultz marked this conversation as resolved.
Show resolved Hide resolved
}

_, err := os.Stat(dir)
if err == nil {
// Directory already exists.
// Read the existing storage.
for _, network := range networks {
currentState, fileExists, err := storage.getCurrentState(network)
for _, chainID := range chainIDs {
currentState, fileExists, err := storage.getCurrentState(chainID)
if err != nil {
return nil, err
}
if fileExists {
storage.currentState[network] = currentState
storage.currentState[chainID] = currentState
}
}
return storage, nil
Expand Down
20 changes: 16 additions & 4 deletions main/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"os"

"github.com/alexliesenfeld/health"
"github.com/ava-labs/avalanchego/api/info"
"github.com/ava-labs/avalanchego/api/metrics"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/message"
Expand Down Expand Up @@ -74,8 +75,9 @@ func main() {
}
logger.Info(fmt.Sprintf("Set config options.%s", overwrittenLog))

// Global P-Chain client used to get subnet validator sets
// Global P-Chain and Info clients used to get subnet validator sets
pChainClient := platformvm.NewClient(cfg.PChainAPIURL)
infoClient := info.NewClient(cfg.InfoAPIURL)

// Initialize all destination clients
logger.Info("Initializing destination clients")
Expand All @@ -98,15 +100,20 @@ func main() {

// Initialize the global app request network
logger.Info("Initializing app request network")
sourceSubnetIDs, sourceBlockchainIDs := cfg.GetSourceIDs()

// The app request network generates P2P networking logs that are verbose at the info level.
// Unless the log level is debug or lower, set the network log level to error to avoid spamming the logs.
networkLogLevel := logging.Error
if logLevel <= logging.Debug {
networkLogLevel = logLevel
}
network, responseChans, err := peers.NewNetwork(networkLogLevel, registerer, sourceSubnetIDs, sourceBlockchainIDs, cfg.InfoAPIURL)
network, responseChans, err := peers.NewNetwork(
networkLogLevel,
registerer,
&cfg,
infoClient,
pChainClient,
)
if err != nil {
logger.Error(
"Failed to create app request network",
Expand Down Expand Up @@ -167,7 +174,12 @@ func main() {
}

// Initialize the database
db, err := database.NewJSONFileStorage(logger, cfg.StorageLocation, sourceBlockchainIDs)
sourceChainIDs := make([]ids.ID, len(cfg.SourceBlockchains))
cam-schultz marked this conversation as resolved.
Show resolved Hide resolved
for i, sourceBlockchain := range cfg.SourceBlockchains {
sourceChainIDs[i] = sourceBlockchain.GetBlockchainID()
}

db, err := database.NewJSONFileStorage(logger, cfg.StorageLocation, sourceChainIDs)
cam-schultz marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
logger.Error(
"Failed to create database",
Expand Down
Loading
Loading