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