github.com/prysmaticlabs/prysm@v1.4.4/spectest/general/phase0/bls/sign_test.go (about)

     1  package bls
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/hex"
     6  	"errors"
     7  	"path"
     8  	"testing"
     9  
    10  	"github.com/ghodss/yaml"
    11  	"github.com/prysmaticlabs/prysm/shared/bls"
    12  	"github.com/prysmaticlabs/prysm/shared/bls/common"
    13  	"github.com/prysmaticlabs/prysm/shared/testutil"
    14  	"github.com/prysmaticlabs/prysm/shared/testutil/require"
    15  	"github.com/prysmaticlabs/prysm/spectest/utils"
    16  )
    17  
    18  func TestSign(t *testing.T) {
    19  	t.Run("blst", testSign)
    20  }
    21  
    22  func testSign(t *testing.T) {
    23  	testFolders, testFolderPath := utils.TestFolders(t, "general", "phase0", "bls/sign/small")
    24  
    25  	for i, folder := range testFolders {
    26  		t.Run(folder.Name(), func(t *testing.T) {
    27  			file, err := testutil.BazelFileBytes(path.Join(testFolderPath, folder.Name(), "data.yaml"))
    28  			require.NoError(t, err)
    29  			test := &SignMsgTest{}
    30  			require.NoError(t, yaml.Unmarshal(file, test))
    31  			pkBytes, err := hex.DecodeString(test.Input.Privkey[2:])
    32  			require.NoError(t, err)
    33  			sk, err := bls.SecretKeyFromBytes(pkBytes)
    34  			if err != nil {
    35  				if test.Output == "" &&
    36  					(errors.Is(err, common.ErrZeroKey) || errors.Is(err, common.ErrSecretUnmarshal)) {
    37  					return
    38  				}
    39  				t.Fatalf("cannot unmarshal secret key: %v", err)
    40  			}
    41  			msgBytes, err := hex.DecodeString(test.Input.Message[2:])
    42  			require.NoError(t, err)
    43  			sig := sk.Sign(msgBytes)
    44  
    45  			if !sig.Verify(sk.PublicKey(), msgBytes) {
    46  				t.Fatal("could not verify signature")
    47  			}
    48  
    49  			outputBytes, err := hex.DecodeString(test.Output[2:])
    50  			require.NoError(t, err)
    51  
    52  			if !bytes.Equal(outputBytes, sig.Marshal()) {
    53  				t.Fatalf("Test Case %d: Signature does not match the expected output. "+
    54  					"Expected %#x but received %#x", i, outputBytes, sig.Marshal())
    55  			}
    56  			t.Log("Success")
    57  		})
    58  	}
    59  }