github.com/MetalBlockchain/metalgo@v1.11.9/vms/components/verify/subnet.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package verify
     5  
     6  import (
     7  	"context"
     8  	"errors"
     9  	"fmt"
    10  
    11  	"github.com/MetalBlockchain/metalgo/ids"
    12  	"github.com/MetalBlockchain/metalgo/snow"
    13  )
    14  
    15  var (
    16  	ErrSameChainID         = errors.New("same chainID")
    17  	ErrMismatchedSubnetIDs = errors.New("mismatched subnetIDs")
    18  )
    19  
    20  // SameSubnet verifies that the provided [ctx] was provided to a chain in the
    21  // same subnet as [peerChainID], but not the same chain. If this verification
    22  // fails, a non-nil error will be returned.
    23  func SameSubnet(ctx context.Context, chainCtx *snow.Context, peerChainID ids.ID) error {
    24  	if peerChainID == chainCtx.ChainID {
    25  		return ErrSameChainID
    26  	}
    27  
    28  	subnetID, err := chainCtx.ValidatorState.GetSubnetID(ctx, peerChainID)
    29  	if err != nil {
    30  		return fmt.Errorf("failed to get subnet of %q: %w", peerChainID, err)
    31  	}
    32  	if chainCtx.SubnetID != subnetID {
    33  		return fmt.Errorf("%w; expected %q got %q", ErrMismatchedSubnetIDs, chainCtx.SubnetID, subnetID)
    34  	}
    35  	return nil
    36  }