github.com/igggame/nebulas-go@v2.1.0+incompatible/crypto/keystore/secp256k1/vrf/secp256k1VRF/secp256k1VRF_test.go (about)

     1  // Copyright 2016 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package secp256k1VRF
    16  
    17  import (
    18  	"bytes"
    19  	"crypto/rand"
    20  	"encoding/hex"
    21  	"fmt"
    22  	"math"
    23  	"testing"
    24  	"time"
    25  
    26  	"github.com/nebulasio/go-nebulas/crypto/keystore/secp256k1"
    27  	"github.com/nebulasio/go-nebulas/util/byteutils"
    28  	// _ "github.com/google/trillian/crypto/keys/der/proto"
    29  )
    30  
    31  const (
    32  	// private key in hex
    33  	privKey = `b02b430d4a9d7120b65038452a6da3f3c716829e5be3665adf934d4798d96ed7`
    34  	// public key in hex
    35  	pubKey = `04e4d0dde330c0b8d8d8b1b2071aa75c3e94f200a3d11ca1d908644eee50c8833a816dc0b2d003fc66187ef6750a56e1b3004d32e6159008400ab92f2ded7b4544`
    36  )
    37  
    38  func TestH1(t *testing.T) {
    39  	for i := 0; i < 10000; i++ {
    40  		m := make([]byte, 100)
    41  		if _, err := rand.Read(m); err != nil {
    42  			t.Fatalf("Failed generating random message: %v", err)
    43  		}
    44  		x, y := H1(m)
    45  		if x == nil {
    46  			t.Errorf("H1(%v)=%v, want curve point", m, x)
    47  		}
    48  		// attention: should not use curve.Params(), that will use elliptic.IsOnCurve()
    49  		if got := curve.IsOnCurve(x, y); !got {
    50  			t.Errorf("H1(%v)=[%v, %v], is not on curve", m, x, y)
    51  		}
    52  	}
    53  }
    54  
    55  func TestH2(t *testing.T) {
    56  	l := 32
    57  	for i := 0; i < 10000; i++ {
    58  		m := make([]byte, 100)
    59  		if _, err := rand.Read(m); err != nil {
    60  			t.Fatalf("Failed generating random message: %v", err)
    61  		}
    62  		x := H2(m)
    63  		if got := len(x.Bytes()); got < 1 || got > l {
    64  			t.Errorf("len(h2(%v)) = %v, want: 1 <= %v <= %v", m, got, got, l)
    65  		}
    66  	}
    67  }
    68  
    69  func TestEmmm(t *testing.T) {
    70  	k, pk := GenerateKey()
    71  	m1 := []byte("da30b4ed14affb62b3719fb5e6952d3733e84e53fe6e955f8e46da503300c985")
    72  	index1, proof1 := k.Evaluate(m1)
    73  	fmt.Println("evaluate index = ", index1)
    74  	fmt.Println("evaluate proof = ", proof1)
    75  
    76  	start := time.Now()
    77  	for i := 0; i < 100; i++ {
    78  		_, _ = k.Evaluate(m1)
    79  	}
    80  	end := time.Now()
    81  	fmt.Println("evaluate x100 total time: ", end.Sub(start))
    82  
    83  	index, _ := pk.ProofToHash(m1, proof1)
    84  	fmt.Println("proof index = ", index)
    85  
    86  	start = time.Now()
    87  	for i := 0; i < 100; i++ {
    88  		_, _ = pk.ProofToHash(m1, proof1)
    89  	}
    90  	end = time.Now()
    91  	fmt.Println("proof x100 total time: ", end.Sub(start))
    92  }
    93  
    94  func TestVRF(t *testing.T) {
    95  	k, pk := GenerateKey()
    96  
    97  	m1 := []byte("data1")
    98  	m2 := []byte("data2")
    99  	m3 := []byte("data2")
   100  	index1, proof1 := k.Evaluate(m1)
   101  	index2, proof2 := k.Evaluate(m2)
   102  	index3, proof3 := k.Evaluate(m3)
   103  	for _, tc := range []struct {
   104  		m     []byte
   105  		index [32]byte
   106  		proof []byte
   107  		err   error
   108  	}{
   109  		{m1, index1, proof1, nil},
   110  		{m2, index2, proof2, nil},
   111  		{m3, index3, proof3, nil},
   112  		{m3, index3, proof2, nil},
   113  		{m3, index3, proof1, ErrInvalidVRF},
   114  	} {
   115  		index, err := pk.ProofToHash(tc.m, tc.proof)
   116  		if got, want := err, tc.err; got != want {
   117  			t.Errorf("ProofToHash(%s, %x): %v, want %v", tc.m, tc.proof, got, want)
   118  		}
   119  		if err != nil {
   120  			continue
   121  		}
   122  		if got, want := index, tc.index; got != want {
   123  			t.Errorf("ProofToInex(%s, %x): %x, want %x", tc.m, tc.proof, got, want)
   124  		}
   125  	}
   126  }
   127  
   128  func TestProofToHash(t *testing.T) {
   129  	bytes, _ := byteutils.FromHex(pubKey)
   130  	pk, err := NewVRFVerifierFromRawKey(bytes)
   131  	if err != nil {
   132  		t.Errorf("NewVRFSigner failure: %v", err)
   133  	}
   134  
   135  	for _, tc := range []struct {
   136  		m     []byte
   137  		index [32]byte
   138  		proof []byte
   139  	}{
   140  		{
   141  			m:     []byte("data1"),
   142  			index: h2i("a2f4f844d46240a86790c177f21422f430b2803c7590f32625079fc13a5fe601"),
   143  			proof: h2b("cc23d0e1e01a20bcee479e944c94febabb8e762fa64b9443fc9dc31d3332e3a7024f4adc2cda4e8847fe67f47ab0084b677996e9325d31840531a2f91d6a5d7d04e54044c12dd5ab7b90a57117a85d6307125496ada896d9823c860c4f492c0096c714705d58ee7d66ee6cffb5f1320c5eab7f92490b0f5759145588efa0b0537d"),
   144  		},
   145  		{
   146  			m:     []byte("data2"),
   147  			index: h2i("008a288a33a2620458a26b6c995d9c16ca46c293562db76985bd1b2a159efc76"),
   148  			proof: h2b("888e0d3191af542c40d0d8b15255e106a133ec9b219b6e26900e07a252e6ab60e510423c34bf74cc602ae2be214bffadfd639793d0a3dccd0e7303be8d0de57604322cef265dfe906cebf30de74b14aa33723435eccea3153fedb5bea70e5c58a8969af97c27e50223bc3b9a8dd8f4a60ec363a78c957f366af075cf83cc43e61c"),
   149  		},
   150  		{
   151  			m:     []byte("data3"),
   152  			index: h2i("9bb53b519519a85c8c6c6739349168c42ae208aed7dadeababf5a067a6ac1313"),
   153  			proof: h2b("96004eb1450c68fcb1ac83e0f09c5311089829762a5e8aecdba1c51d703250d79bc9ffeb72c0c5645da6c3d2d59a5c6428b1d3a0075d75b89bae8b539453e3af044a472b26f259bd5a84f05ec8fe1d7858d6f5606adcb6febeef113a2ff4ff69d5166ebbd3c3a78c451d751490eeb37fd39358fb2fad8ae218e3fc5177fe2e9b37"),
   154  		},
   155  	} {
   156  
   157  		bytes, _ := byteutils.FromHex(privKey)
   158  		k, err := NewVRFSignerFromRawKey(bytes)
   159  		idx, proof := k.Evaluate(tc.m)
   160  		fmt.Println("=======")
   161  		fmt.Println(byteutils.Hex(idx[0:]))
   162  		fmt.Println(byteutils.Hex(proof))
   163  
   164  		index, err := pk.ProofToHash(tc.m, tc.proof)
   165  		if err != nil {
   166  			t.Errorf("ProofToHash(%s, %x): %v, want nil", tc.m, tc.proof, err)
   167  			continue
   168  		}
   169  		if got, want := index, tc.index; got != want {
   170  			t.Errorf("ProofToHash(%s, %x): %x, want %x", tc.m, tc.proof, got, want)
   171  		}
   172  	}
   173  }
   174  
   175  func TestReadFromOpenSSL(t *testing.T) {
   176  	for _, tc := range []struct {
   177  		priv string
   178  		pub  string
   179  	}{
   180  		{privKey, pubKey},
   181  	} {
   182  		// Private VRF Key
   183  		bytes, _ := byteutils.FromHex(tc.priv)
   184  		signer, err := NewVRFSignerFromRawKey(bytes)
   185  		if err != nil {
   186  			t.Errorf("NewVRFSigner failure: %v", err)
   187  		}
   188  
   189  		// Public VRF key
   190  		bytes, _ = byteutils.FromHex(tc.pub)
   191  		verifier, err := NewVRFVerifierFromRawKey(bytes)
   192  		if err != nil {
   193  			t.Errorf("NewVRFSigner failure: %v", err)
   194  		}
   195  
   196  		// Evaluate and verify.
   197  		m := []byte("M")
   198  		_, proof := signer.Evaluate(m)
   199  		if _, err := verifier.ProofToHash(m, proof); err != nil {
   200  			t.Errorf("Failed verifying VRF proof")
   201  		}
   202  	}
   203  }
   204  
   205  func TestRightTruncateProof(t *testing.T) {
   206  	k, pk := GenerateKey()
   207  
   208  	data := []byte("data")
   209  	_, proof := k.Evaluate(data)
   210  	proofLen := len(proof)
   211  	for i := 0; i < proofLen; i++ {
   212  		proof = proof[:len(proof)-1]
   213  		if _, err := pk.ProofToHash(data, proof); err == nil {
   214  			t.Errorf("Verify unexpectedly succeeded after truncating %v bytes from the end of proof", i)
   215  		}
   216  	}
   217  }
   218  
   219  func TestLeftTruncateProof(t *testing.T) {
   220  	k, pk := GenerateKey()
   221  
   222  	data := []byte("data")
   223  	_, proof := k.Evaluate(data)
   224  	proofLen := len(proof)
   225  	for i := 0; i < proofLen; i++ {
   226  		proof = proof[1:]
   227  		if _, err := pk.ProofToHash(data, proof); err == nil {
   228  			t.Errorf("Verify unexpectedly succeeded after truncating %v bytes from the beginning of proof", i)
   229  		}
   230  	}
   231  }
   232  
   233  func TestBitFlip(t *testing.T) {
   234  	k, pk := GenerateKey()
   235  
   236  	data := []byte("data")
   237  	_, proof := k.Evaluate(data)
   238  	for i := 0; i < len(proof)*8; i++ {
   239  		// Flip bit in position i.
   240  		if _, err := pk.ProofToHash(data, flipBit(proof, i)); err == nil {
   241  			t.Errorf("Verify unexpectedly succeeded after flipping bit %v of vrf", i)
   242  		}
   243  	}
   244  }
   245  
   246  func flipBit(a []byte, pos int) []byte {
   247  	index := int(math.Floor(float64(pos) / 8))
   248  	b := byte(a[index])
   249  	b ^= (1 << uint(math.Mod(float64(pos), 8.0)))
   250  
   251  	var buf bytes.Buffer
   252  	buf.Write(a[:index])
   253  	buf.Write([]byte{b})
   254  	buf.Write(a[index+1:])
   255  	return buf.Bytes()
   256  }
   257  
   258  func TestVectors(t *testing.T) {
   259  	bytes, _ := byteutils.FromHex(privKey)
   260  	k, err := NewVRFSignerFromRawKey(bytes)
   261  	if err != nil {
   262  		t.Errorf("NewVRFSigner failure: %v", err)
   263  	}
   264  	bytes, _ = byteutils.FromHex(pubKey)
   265  	pk, err := NewVRFVerifierFromRawKey(bytes)
   266  	if err != nil {
   267  		t.Errorf("NewVRFSigner failure: %v", err)
   268  	}
   269  	for _, tc := range []struct {
   270  		m     []byte
   271  		index [32]byte
   272  	}{
   273  		{
   274  			m:     []byte("test"),
   275  			index: h2i("c095a258b89a5fbf0790e45cd2b1a31c1723f0f99c7df3df98e03eef2a4a25af"),
   276  		},
   277  		{
   278  			m:     nil,
   279  			index: h2i("19a1da136a3dadfd4ffb2e95d0b236b72e7bd448541a46fde595acd5052775cb"),
   280  		},
   281  	} {
   282  		index, proof := k.Evaluate(tc.m)
   283  		if got, want := index, tc.index; got != want {
   284  			t.Errorf("Evaluate(%s).Index: %x, want %x", tc.m, got, want)
   285  		}
   286  		index2, err := pk.ProofToHash(tc.m, proof)
   287  		if err != nil {
   288  			t.Errorf("ProofToHash(%s): %v", tc.m, err)
   289  		}
   290  		if got, want := index2, index; got != want {
   291  			t.Errorf("ProofToHash(%s): %x, want %x", tc.m, got, want)
   292  		}
   293  	}
   294  }
   295  
   296  func h2i(h string) [32]byte {
   297  	b, err := hex.DecodeString(h)
   298  	if err != nil {
   299  		panic("Invalid hex")
   300  	}
   301  	var i [32]byte
   302  	copy(i[:], b)
   303  	return i
   304  }
   305  
   306  func h2b(h string) []byte {
   307  	b, err := hex.DecodeString(h)
   308  	if err != nil {
   309  		panic("Invalid hex")
   310  	}
   311  	return b
   312  }
   313  
   314  func Test256VRF(t *testing.T) {
   315  
   316  	seckey, err := byteutils.FromHex(privKey)
   317  	if err != nil {
   318  		t.Errorf("load priv err: %v", err)
   319  	}
   320  	ecdsaPriv, err := secp256k1.ToECDSAPrivateKey(seckey)
   321  	if err != nil {
   322  		t.Errorf("ecdsa err: %v", err)
   323  	}
   324  
   325  	signer, err := NewVRFSigner(ecdsaPriv)
   326  	if err != nil {
   327  		t.Errorf("new signer err: %v", err)
   328  	}
   329  
   330  	data := []byte("b10c1203d5ae6d4d069d5f520eb060f2f5fb74e942f391e7cadbc2b5148dfbcb")
   331  	sIndex, proof := signer.Evaluate(data)
   332  
   333  	seckeyPub, err := byteutils.FromHex(pubKey)
   334  
   335  	priv := new(secp256k1.PrivateKey)
   336  	err = priv.Decode(seckey)
   337  	if err != nil {
   338  		t.Errorf("decode priv err: %v", err)
   339  	}
   340  
   341  	epub, err := priv.PublicKey().Encoded()
   342  	if err != nil {
   343  		t.Errorf("encode pub err: %v", err)
   344  	}
   345  	if !bytes.Equal(seckeyPub, epub) {
   346  		t.Errorf("mismatched priv/pub err: %v", err)
   347  	}
   348  
   349  	verifier, err := NewVRFVerifierFromRawKey(seckeyPub)
   350  	if err != nil {
   351  		t.Errorf("new verifier err: %v", err)
   352  	}
   353  
   354  	vIndex, err := verifier.ProofToHash(data, proof)
   355  	if err != nil {
   356  		t.Errorf("exec proof err: %v", err)
   357  	}
   358  
   359  	if !bytes.Equal(sIndex[0:], vIndex[0:]) {
   360  		t.Errorf("verification failed")
   361  	}
   362  }