github.com/cloudflare/circl@v1.5.0/ecc/goldilocks/point_test.go (about)

     1  package goldilocks_test
     2  
     3  import (
     4  	"crypto/rand"
     5  	"encoding"
     6  	"testing"
     7  
     8  	"github.com/cloudflare/circl/ecc/goldilocks"
     9  	"github.com/cloudflare/circl/internal/test"
    10  )
    11  
    12  func randomPoint() *goldilocks.Point {
    13  	var k goldilocks.Scalar
    14  	_, _ = rand.Read(k[:])
    15  	return goldilocks.Curve{}.ScalarBaseMult(&k)
    16  }
    17  
    18  func TestPointAdd(t *testing.T) {
    19  	const testTimes = 1 << 10
    20  	var e goldilocks.Curve
    21  	for i := 0; i < testTimes; i++ {
    22  		P := randomPoint()
    23  		// 16P = 2^4P
    24  		got := e.Double(e.Double(e.Double(e.Double(P))))
    25  		// 16P = P+P...+P
    26  		Q := e.Identity()
    27  		for j := 0; j < 16; j++ {
    28  			Q = e.Add(Q, P)
    29  		}
    30  		want := Q
    31  		if !e.IsOnCurve(got) || !e.IsOnCurve(want) || !got.IsEqual(want) {
    32  			test.ReportError(t, got, want, P)
    33  		}
    34  	}
    35  }
    36  
    37  func TestPointNeg(t *testing.T) {
    38  	const testTimes = 1 << 10
    39  	var e goldilocks.Curve
    40  	for i := 0; i < testTimes; i++ {
    41  		P := randomPoint()
    42  		Q := *P
    43  		Q.Neg()
    44  		R := e.Add(P, &Q)
    45  		got := R.IsIdentity()
    46  		want := true
    47  		if got != want {
    48  			test.ReportError(t, got, want, P)
    49  		}
    50  	}
    51  }
    52  
    53  func TestPointAffine(t *testing.T) {
    54  	const testTimes = 1 << 10
    55  	for i := 0; i < testTimes; i++ {
    56  		got := randomPoint()
    57  		x, y := got.ToAffine()
    58  		want, err := goldilocks.FromAffine(&x, &y)
    59  		if !got.IsEqual(want) || err != nil {
    60  			test.ReportError(t, got, want)
    61  		}
    62  	}
    63  }
    64  
    65  func TestPointMarshal(t *testing.T) {
    66  	const testTimes = 1 << 10
    67  	var want error
    68  	for i := 0; i < testTimes; i++ {
    69  		var P interface{} = randomPoint()
    70  		mar, _ := P.(encoding.BinaryMarshaler)
    71  		data, got := mar.MarshalBinary()
    72  		if got != want {
    73  			test.ReportError(t, got, want, P)
    74  		}
    75  		unmar, _ := P.(encoding.BinaryUnmarshaler)
    76  		got = unmar.UnmarshalBinary(data)
    77  		if got != want {
    78  			test.ReportError(t, got, want, P)
    79  		}
    80  	}
    81  }
    82  
    83  func BenchmarkPoint(b *testing.B) {
    84  	P := randomPoint()
    85  	Q := randomPoint()
    86  	b.Run("ToAffine", func(b *testing.B) {
    87  		for i := 0; i < b.N; i++ {
    88  			P.ToAffine()
    89  		}
    90  	})
    91  	b.Run("Add", func(b *testing.B) {
    92  		for i := 0; i < b.N; i++ {
    93  			P.Add(Q)
    94  		}
    95  	})
    96  	b.Run("Double", func(b *testing.B) {
    97  		for i := 0; i < b.N; i++ {
    98  			P.Double()
    99  		}
   100  	})
   101  }