aboutsummaryrefslogtreecommitdiff
path: root/pkg/oaddr/oaddr_test.go
blob: 549bd67551323a302e9840b2764648c4724abed2 (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
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
package oaddr

import (
	"crypto"
	"crypto/ed25519"
	"testing"

	bed25519 "github.com/cretz/bine/torutil/ed25519"
	"sauteed-onions.org/onion-csr/internal/testonly"
)

const (
	testPriv = "a4007fabb23fae0f50fc45481553bf7d5d26b9fd8d76142c572606a6ebd7a2c1"
	testPub  = "da67efa9e06e724d999f8e0409b4a5a08aebd26005b63bef90d51a241d631cfd"
	testAddr = "3jt67kpanzze3gm7rycatnffucfoxutaaw3dx34q2uncihlddt6tq3ad.onion"
)

func TestNew(t *testing.T) {
	for _, table := range []struct {
		desc string
		pub  []byte
		want OnionAddress
	}{
		{"too short key", testonly.DecodeHex(t, testPub)[1:], newAddr(t, testPub)},
		{"too long key", append(testonly.DecodeHex(t, testPub), 0xff), newAddr(t, testPub)},
		{"valid", testonly.DecodeHex(t, testPub), newAddr(t, testPub)},
	} {
		addr, err := New(table.pub)
		if got, want := err != nil, table.desc != "valid"; got != want {
			t.Errorf("%s: got error %v but wanted %v: %v", table.desc, got, want, err)
		}
		if err != nil {
			continue
		}
		if got, want := addr, table.want; got != want {
			t.Errorf("%s: got address\n%x\nbut wanted\n%x", table.desc, got[:], want[:])
		}
	}
}

func TestNewFromSigner(t *testing.T) {
	for _, table := range []struct {
		desc string
		priv crypto.Signer
		want OnionAddress
	}{
		{"rsa key", testonly.RSAPriv(t), OnionAddress{}},
		{"valid", testonly.Ed25519Priv(t, testPriv), newAddr(t, testPub)},
		{"valid", bed25519.FromCryptoPrivateKey(testonly.Ed25519Priv(t, testPriv)).PrivateKey(), newAddr(t, testPub)},
	} {
		addr, err := NewFromSigner(table.priv)
		if got, want := err != nil, table.desc != "valid"; got != want {
			t.Errorf("%s: got error %v but wanted %v: %v", table.desc, got, want, err)
		}
		if err != nil {
			continue
		}
		if got, want := addr, table.want; got != want {
			t.Errorf("%s: got address\n%x\nbut wanted\n%x", table.desc, got[:], want[:])
		}
	}
}

func TestString(t *testing.T) {
	addr := newAddr(t, testPub)
	want := testAddr
	if got, want := addr.String(), want; got != want {
		t.Errorf("got address\n%s\nbut wanted\n%s", got, want)
	}
}

func newAddr(t *testing.T, pub string) (addr OnionAddress) {
	t.Helper()
	b := testonly.DecodeHex(t, pub)
	if got, want := len(b), ed25519.PublicKeySize; got != want {
		t.Fatalf("invalid public key size: %d", got)
	}
	copy(addr[:], b)
	return
}