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