File: german_test.go

package info (click to toggle)
golang-github-nebulouslabs-entropy-mnemonics 0.0~git20170316.0.7b01a64-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 176 kB
  • sloc: makefile: 2
file content (92 lines) | stat: -rw-r--r-- 2,231 bytes parent folder | download | duplicates (2)
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
package mnemonics

import (
	"bytes"
	"crypto/rand"
	"testing"
	"unicode/utf8"

	"golang.org/x/text/unicode/norm"
)

// TestGermanDictionary checks that the german dictionary is well formed.
func TestGermanDictionary(t *testing.T) {
	// Check for sane constants.
	if German != "german" {
		t.Error("unexpected identifier for german dictionary")
	}
	if GermanUniquePrefixLen != 4 {
		t.Error("unexpected prefix len for german dictionary")
	}

	// Check that the dictionary has well formed elements, and no repeats.
	gerMap := make(map[string]struct{})
	for _, word := range germanDictionary {
		// Check that the word is long enough.
		if utf8.RuneCountInString(word) < GermanUniquePrefixLen {
			t.Fatal("found a short word:", word)
		}

		// Check that the word is normalized.
		newWord := norm.NFC.String(word)
		if newWord != word {
			t.Error("found a non-normalized word:", word)
		}

		// Fetch the prefix, composed of the first GermanUniquePrefixLen runes.
		var prefix []byte
		var runeCount int
		for _, r := range word {
			encR := make([]byte, utf8.RuneLen(r))
			utf8.EncodeRune(encR, r)
			prefix = append(prefix, encR...)

			runeCount++
			if runeCount == GermanUniquePrefixLen {
				break
			}
		}

		// Check that the prefix is unique.
		str := string(prefix)
		_, exists := gerMap[str]
		if exists {
			t.Error("found a prefix conflict:", word)
		}
		gerMap[str] = struct{}{}
	}

	// Do some conversions with the german dictionary.
	for i := 1; i <= 32; i++ {
		for j := 0; j < 5; j++ {
			entropy := make([]byte, i)
			_, err := rand.Read(entropy)
			if err != nil {
				t.Fatal(err)
			}
			phrase, err := ToPhrase(entropy, German)
			if err != nil {
				t.Fatal(err)
			}
			check, err := FromPhrase(phrase, German)
			if err != nil {
				t.Fatal(err)
			}
			if bytes.Compare(entropy, check) != 0 {
				t.Error("conversion check failed for the german dictionary")
			}
		}
	}

	// Check that words in a phrase can be altered according to the prefix
	// rule.
	entropy := []byte{1, 2, 3, 4}
	phrase := Phrase{"bete", "Rieglfffffzzzz", "Abundans"}
	check, err := FromPhrase(phrase, German)
	if err != nil {
		t.Fatal(err)
	}
	if bytes.Compare(entropy, check) != 0 {
		t.Error("phrase substitution failed")
	}
}