summaryrefslogtreecommitdiffhomepage
path: root/types/key/key_test.go
blob: 7a2155ef0c5f39fb7f8c7622e0f68e0bb828263e (plain)
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
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package key

import (
	"testing"

	"tailscale.com/types/wgkey"
)

func TestTextUnmarshal(t *testing.T) {
	p := Public{1, 2}
	text, err := p.MarshalText()
	if err != nil {
		t.Fatal(err)
	}
	var p2 Public
	if err := p2.UnmarshalText(text); err != nil {
		t.Fatal(err)
	}
	if p != p2 {
		t.Fatalf("mismatch; got %x want %x", p2, p)
	}
}

func TestClamping(t *testing.T) {
	t.Run("NewPrivate", func(t *testing.T) { testClamping(t, NewPrivate) })

	// Also test the wgkey package, as their behavior should match.
	t.Run("wgkey", func(t *testing.T) {
		testClamping(t, func() Private {
			k, err := wgkey.NewPrivate()
			if err != nil {
				t.Fatal(err)
			}
			return Private(k)
		})
	})
}

func testClamping(t *testing.T, newKey func() Private) {
	for i := 0; i < 100; i++ {
		k := newKey()
		if k[0]&0b111 != 0 {
			t.Fatalf("Bogus clamping in first byte: %#08b", k[0])
			return
		}
		if k[31]>>6 != 1 {
			t.Fatalf("Bogus clamping in last byte: %#08b", k[0])
		}
	}
}