github.com/MetalBlockchain/metalgo@v1.11.9/vms/platformvm/warp/test_signer.go (about)

     1  // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
     2  // See the file LICENSE for licensing terms.
     3  
     4  package warp
     5  
     6  import (
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/MetalBlockchain/metalgo/ids"
    12  	"github.com/MetalBlockchain/metalgo/utils/constants"
    13  	"github.com/MetalBlockchain/metalgo/utils/crypto/bls"
    14  )
    15  
    16  // SignerTests is a list of all signer tests
    17  var SignerTests = map[string]func(t *testing.T, s Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID){
    18  	"WrongChainID":   TestWrongChainID,
    19  	"WrongNetworkID": TestWrongNetworkID,
    20  	"Verifies":       TestVerifies,
    21  }
    22  
    23  // Test that using a random SourceChainID results in an error
    24  func TestWrongChainID(t *testing.T, s Signer, _ *bls.SecretKey, _ uint32, _ ids.ID) {
    25  	require := require.New(t)
    26  
    27  	msg, err := NewUnsignedMessage(
    28  		constants.UnitTestID,
    29  		ids.GenerateTestID(),
    30  		[]byte("payload"),
    31  	)
    32  	require.NoError(err)
    33  
    34  	_, err = s.Sign(msg)
    35  	// TODO: require error to be ErrWrongSourceChainID
    36  	require.Error(err) //nolint:forbidigo // currently returns grpc errors too
    37  }
    38  
    39  // Test that using a different networkID results in an error
    40  func TestWrongNetworkID(t *testing.T, s Signer, _ *bls.SecretKey, networkID uint32, blockchainID ids.ID) {
    41  	require := require.New(t)
    42  
    43  	msg, err := NewUnsignedMessage(
    44  		networkID+1,
    45  		blockchainID,
    46  		[]byte("payload"),
    47  	)
    48  	require.NoError(err)
    49  
    50  	_, err = s.Sign(msg)
    51  	// TODO: require error to be ErrWrongNetworkID
    52  	require.Error(err) //nolint:forbidigo // currently returns grpc errors too
    53  }
    54  
    55  // Test that a signature generated with the signer verifies correctly
    56  func TestVerifies(t *testing.T, s Signer, sk *bls.SecretKey, networkID uint32, chainID ids.ID) {
    57  	require := require.New(t)
    58  
    59  	msg, err := NewUnsignedMessage(
    60  		networkID,
    61  		chainID,
    62  		[]byte("payload"),
    63  	)
    64  	require.NoError(err)
    65  
    66  	sigBytes, err := s.Sign(msg)
    67  	require.NoError(err)
    68  
    69  	sig, err := bls.SignatureFromBytes(sigBytes)
    70  	require.NoError(err)
    71  
    72  	pk := bls.PublicFromSecretKey(sk)
    73  	msgBytes := msg.Bytes()
    74  	require.True(bls.Verify(pk, sig, msgBytes))
    75  }