File: point_test.go

package info (click to toggle)
golang-github-cloudflare-circl 1.0.0%2B20200724-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 5,788 kB
  • sloc: asm: 19,418; ansic: 1,289; makefile: 54
file content (101 lines) | stat: -rw-r--r-- 2,068 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
package goldilocks_test

import (
	"crypto/rand"
	"encoding"
	"testing"

	"github.com/cloudflare/circl/ecc/goldilocks"
	"github.com/cloudflare/circl/internal/test"
)

func randomPoint() *goldilocks.Point {
	var k goldilocks.Scalar
	_, _ = rand.Read(k[:])
	return goldilocks.Curve{}.ScalarBaseMult(&k)
}

func TestPointAdd(t *testing.T) {
	const testTimes = 1 << 10
	var e goldilocks.Curve
	for i := 0; i < testTimes; i++ {
		P := randomPoint()
		// 16P = 2^4P
		got := e.Double(e.Double(e.Double(e.Double(P))))
		// 16P = P+P...+P
		Q := e.Identity()
		for j := 0; j < 16; j++ {
			Q = e.Add(Q, P)
		}
		want := Q
		if !e.IsOnCurve(got) || !e.IsOnCurve(want) || !got.IsEqual(want) {
			test.ReportError(t, got, want, P)
		}
	}
}

func TestPointNeg(t *testing.T) {
	const testTimes = 1 << 10
	var e goldilocks.Curve
	for i := 0; i < testTimes; i++ {
		P := randomPoint()
		Q := *P
		Q.Neg()
		R := e.Add(P, &Q)
		got := R.IsIdentity()
		want := true
		if got != want {
			test.ReportError(t, got, want, P)
		}
	}
}

func TestPointAffine(t *testing.T) {
	const testTimes = 1 << 10
	for i := 0; i < testTimes; i++ {
		got := randomPoint()
		x, y := got.ToAffine()
		want, err := goldilocks.FromAffine(&x, &y)
		if !got.IsEqual(want) || err != nil {
			test.ReportError(t, got, want)
		}
	}
}

func TestPointMarshal(t *testing.T) {
	const testTimes = 1 << 10
	var want error
	for i := 0; i < testTimes; i++ {
		var P interface{} = randomPoint()
		mar, _ := P.(encoding.BinaryMarshaler)
		data, got := mar.MarshalBinary()
		if got != want {
			test.ReportError(t, got, want, P)
		}
		unmar, _ := P.(encoding.BinaryUnmarshaler)
		got = unmar.UnmarshalBinary(data)
		if got != want {
			test.ReportError(t, got, want, P)
		}
	}
}

func BenchmarkPoint(b *testing.B) {
	P := randomPoint()
	Q := randomPoint()
	b.Run("ToAffine", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			P.ToAffine()
		}
	})
	b.Run("Add", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			P.Add(Q)
		}
	})
	b.Run("Double", func(b *testing.B) {
		for i := 0; i < b.N; i++ {
			P.Double()
		}
	})
}