github.com/aquanetwork/aquachain@v1.7.8/crypto/secp256k1/secp256_test.go (about)

     1  // Copyright 2015 Jeffrey Wilcke, Felix Lange, Gustav Simonsson. All rights reserved.
     2  // Use of this source code is governed by a BSD-style license that can be found in
     3  // the LICENSE file.
     4  
     5  // +build gccgo cgo
     6  
     7  package secp256k1
     8  
     9  import (
    10  	"bytes"
    11  	"crypto/ecdsa"
    12  	"crypto/elliptic"
    13  	"crypto/rand"
    14  	"encoding/hex"
    15  	"testing"
    16  
    17  	"gitlab.com/aquachain/aquachain/common/math"
    18  	"gitlab.com/aquachain/aquachain/crypto/randentropy"
    19  )
    20  
    21  const TestCount = 1000
    22  
    23  func generateKeyPair() (pubkey, privkey []byte) {
    24  	key, err := ecdsa.GenerateKey(S256(), rand.Reader)
    25  	if err != nil {
    26  		panic(err)
    27  	}
    28  	pubkey = elliptic.Marshal(S256(), key.X, key.Y)
    29  	return pubkey, math.PaddedBigBytes(key.D, 32)
    30  }
    31  
    32  func randSig() []byte {
    33  	sig := randentropy.GetEntropyCSPRNG(65)
    34  	sig[32] &= 0x70
    35  	sig[64] %= 4
    36  	return sig
    37  }
    38  
    39  // tests for malleability
    40  // highest bit of signature ECDSA s value must be 0, in the 33th byte
    41  func compactSigCheck(t *testing.T, sig []byte) {
    42  	var b int = int(sig[32])
    43  	if b < 0 {
    44  		t.Errorf("highest bit is negative: %d", b)
    45  	}
    46  	if ((b >> 7) == 1) != ((b & 0x80) == 0x80) {
    47  		t.Errorf("highest bit: %d bit >> 7: %d", b, b>>7)
    48  	}
    49  	if (b & 0x80) == 0x80 {
    50  		t.Errorf("highest bit: %d bit & 0x80: %d", b, b&0x80)
    51  	}
    52  }
    53  
    54  func TestSignatureValidity(t *testing.T) {
    55  	pubkey, seckey := generateKeyPair()
    56  	msg := randentropy.GetEntropyCSPRNG(32)
    57  	sig, err := Sign(msg, seckey)
    58  	if err != nil {
    59  		t.Errorf("signature error: %s", err)
    60  	}
    61  	compactSigCheck(t, sig)
    62  	if len(pubkey) != 65 {
    63  		t.Errorf("pubkey length mismatch: want: 65 have: %d", len(pubkey))
    64  	}
    65  	if len(seckey) != 32 {
    66  		t.Errorf("seckey length mismatch: want: 32 have: %d", len(seckey))
    67  	}
    68  	if len(sig) != 65 {
    69  		t.Errorf("sig length mismatch: want: 65 have: %d", len(sig))
    70  	}
    71  	recid := int(sig[64])
    72  	if recid > 4 || recid < 0 {
    73  		t.Errorf("sig recid mismatch: want: within 0 to 4 have: %d", int(sig[64]))
    74  	}
    75  }
    76  
    77  func TestInvalidRecoveryID(t *testing.T) {
    78  	_, seckey := generateKeyPair()
    79  	msg := randentropy.GetEntropyCSPRNG(32)
    80  	sig, _ := Sign(msg, seckey)
    81  	sig[64] = 99
    82  	_, err := RecoverPubkey(msg, sig)
    83  	if err != ErrInvalidRecoveryID {
    84  		t.Fatalf("got %q, want %q", err, ErrInvalidRecoveryID)
    85  	}
    86  }
    87  
    88  func TestSignAndRecover(t *testing.T) {
    89  	pubkey1, seckey := generateKeyPair()
    90  	msg := randentropy.GetEntropyCSPRNG(32)
    91  	sig, err := Sign(msg, seckey)
    92  	if err != nil {
    93  		t.Errorf("signature error: %s", err)
    94  	}
    95  	pubkey2, err := RecoverPubkey(msg, sig)
    96  	if err != nil {
    97  		t.Errorf("recover error: %s", err)
    98  	}
    99  	if !bytes.Equal(pubkey1, pubkey2) {
   100  		t.Errorf("pubkey mismatch: want: %x have: %x", pubkey1, pubkey2)
   101  	}
   102  }
   103  
   104  func TestSignDeterministic(t *testing.T) {
   105  	_, seckey := generateKeyPair()
   106  	msg := make([]byte, 32)
   107  	copy(msg, "hi there")
   108  
   109  	sig1, err := Sign(msg, seckey)
   110  	if err != nil {
   111  		t.Fatal(err)
   112  	}
   113  	sig2, err := Sign(msg, seckey)
   114  	if err != nil {
   115  		t.Fatal(err)
   116  	}
   117  	if !bytes.Equal(sig1, sig2) {
   118  		t.Fatal("signatures not equal")
   119  	}
   120  }
   121  
   122  func TestRandomMessagesWithSameKey(t *testing.T) {
   123  	pubkey, seckey := generateKeyPair()
   124  	keys := func() ([]byte, []byte) {
   125  		return pubkey, seckey
   126  	}
   127  	signAndRecoverWithRandomMessages(t, keys)
   128  }
   129  
   130  func TestRandomMessagesWithRandomKeys(t *testing.T) {
   131  	keys := func() ([]byte, []byte) {
   132  		pubkey, seckey := generateKeyPair()
   133  		return pubkey, seckey
   134  	}
   135  	signAndRecoverWithRandomMessages(t, keys)
   136  }
   137  
   138  func signAndRecoverWithRandomMessages(t *testing.T, keys func() ([]byte, []byte)) {
   139  	for i := 0; i < TestCount; i++ {
   140  		pubkey1, seckey := keys()
   141  		msg := randentropy.GetEntropyCSPRNG(32)
   142  		sig, err := Sign(msg, seckey)
   143  		if err != nil {
   144  			t.Fatalf("signature error: %s", err)
   145  		}
   146  		if sig == nil {
   147  			t.Fatal("signature is nil")
   148  		}
   149  		compactSigCheck(t, sig)
   150  
   151  		// TODO: why do we flip around the recovery id?
   152  		sig[len(sig)-1] %= 4
   153  
   154  		pubkey2, err := RecoverPubkey(msg, sig)
   155  		if err != nil {
   156  			t.Fatalf("recover error: %s", err)
   157  		}
   158  		if pubkey2 == nil {
   159  			t.Error("pubkey is nil")
   160  		}
   161  		if !bytes.Equal(pubkey1, pubkey2) {
   162  			t.Fatalf("pubkey mismatch: want: %x have: %x", pubkey1, pubkey2)
   163  		}
   164  	}
   165  }
   166  
   167  func TestRecoveryOfRandomSignature(t *testing.T) {
   168  	pubkey1, _ := generateKeyPair()
   169  	msg := randentropy.GetEntropyCSPRNG(32)
   170  
   171  	for i := 0; i < TestCount; i++ {
   172  		// recovery can sometimes work, but if so should always give wrong pubkey
   173  		pubkey2, _ := RecoverPubkey(msg, randSig())
   174  		if bytes.Equal(pubkey1, pubkey2) {
   175  			t.Fatalf("iteration: %d: pubkey mismatch: do NOT want %x: ", i, pubkey2)
   176  		}
   177  	}
   178  }
   179  
   180  func TestRandomMessagesAgainstValidSig(t *testing.T) {
   181  	pubkey1, seckey := generateKeyPair()
   182  	msg := randentropy.GetEntropyCSPRNG(32)
   183  	sig, _ := Sign(msg, seckey)
   184  
   185  	for i := 0; i < TestCount; i++ {
   186  		msg = randentropy.GetEntropyCSPRNG(32)
   187  		pubkey2, _ := RecoverPubkey(msg, sig)
   188  		// recovery can sometimes work, but if so should always give wrong pubkey
   189  		if bytes.Equal(pubkey1, pubkey2) {
   190  			t.Fatalf("iteration: %d: pubkey mismatch: do NOT want %x: ", i, pubkey2)
   191  		}
   192  	}
   193  }
   194  
   195  // Useful when the underlying libsecp256k1 API changes to quickly
   196  // check only recover function without use of signature function
   197  func TestRecoverSanity(t *testing.T) {
   198  	msg, _ := hex.DecodeString("ce0677bb30baa8cf067c88db9811f4333d131bf8bcf12fe7065d211dce971008")
   199  	sig, _ := hex.DecodeString("90f27b8b488db00b00606796d2987f6a5f59ae62ea05effe84fef5b8b0e549984a691139ad57a3f0b906637673aa2f63d1f55cb1a69199d4009eea23ceaddc9301")
   200  	pubkey1, _ := hex.DecodeString("04e32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a0a2b2667f7e725ceea70c673093bf67663e0312623c8e091b13cf2c0f11ef652")
   201  	pubkey2, err := RecoverPubkey(msg, sig)
   202  	if err != nil {
   203  		t.Fatalf("recover error: %s", err)
   204  	}
   205  	if !bytes.Equal(pubkey1, pubkey2) {
   206  		t.Errorf("pubkey mismatch: want: %x have: %x", pubkey1, pubkey2)
   207  	}
   208  }
   209  
   210  func BenchmarkSign(b *testing.B) {
   211  	_, seckey := generateKeyPair()
   212  	msg := randentropy.GetEntropyCSPRNG(32)
   213  	b.ResetTimer()
   214  
   215  	for i := 0; i < b.N; i++ {
   216  		Sign(msg, seckey)
   217  	}
   218  }
   219  
   220  func BenchmarkRecover(b *testing.B) {
   221  	msg := randentropy.GetEntropyCSPRNG(32)
   222  	_, seckey := generateKeyPair()
   223  	sig, _ := Sign(msg, seckey)
   224  	b.ResetTimer()
   225  
   226  	for i := 0; i < b.N; i++ {
   227  		RecoverPubkey(msg, sig)
   228  	}
   229  }