Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

digest_test.gno

2.20 Kb · 83 lines
 1package rulecalc
 2
 3import "testing"
 4
 5func apps2() []App {
 6	return []App{
 7		{Title: "Alpha", PkgPath: "gno.land/r/x/alpha", Payout: address("g1alpha")},
 8		{Title: "Beta", PkgPath: "gno.land/r/x/beta", Payout: address("g1beta")},
 9	}
10}
11
12func TestAppsDigestStable(t *testing.T) {
13	a := AppsDigest(apps2(), "salt")
14	b := AppsDigest(apps2(), "salt")
15	if a != b {
16		t.Fatal("same input, different digest")
17	}
18	if len(a) != 64 {
19		t.Fatalf("want 64 hex chars, got %d", len(a))
20	}
21}
22
23func TestAppsDigestKnownVector(t *testing.T) {
24	// sha256("Alpha|gno.land/r/x/alpha|g1alpha\nBeta|gno.land/r/x/beta|g1beta\nsalt")
25	// computed independently: printf 'Alpha|...\nBeta|...\nsalt' | sha256sum
26	want := "451fc91dfae0103fc7f9a91c168aa15c290f0bbe7217e9acfc900c32ababe09a"
27	if got := AppsDigest(apps2(), "salt"); got != want {
28		t.Fatalf("digest mismatch: got %s", got)
29	}
30}
31
32func TestAppsDigestSensitive(t *testing.T) {
33	base := AppsDigest(apps2(), "salt")
34
35	swapped := apps2()
36	swapped[0], swapped[1] = swapped[1], swapped[0]
37	if AppsDigest(swapped, "salt") == base {
38		t.Error("order change not detected")
39	}
40
41	payout := apps2()
42	payout[1].Payout = address("g1other")
43	if AppsDigest(payout, "salt") == base {
44		t.Error("payout change not detected")
45	}
46
47	if AppsDigest(apps2(), "pepper") == base {
48		t.Error("salt change not detected")
49	}
50}
51
52func TestAppsDigestRejectsSeparators(t *testing.T) {
53	bad := [][]App{
54		{{Title: "A|B", PkgPath: "p", Payout: address("g1")}},
55		{{Title: "A", PkgPath: "p\nq", Payout: address("g1")}},
56		{{Title: "A", PkgPath: "p", Payout: address("g1|x")}},
57	}
58	for i, apps := range bad {
59		func() {
60			defer func() {
61				if recover() == nil {
62					t.Errorf("case %d: expected panic", i)
63				}
64			}()
65			AppsDigest(apps, "salt")
66		}()
67	}
68}
69
70// A salt holding application lines would let the same digest open to a shorter
71// list: [A, B]+salt and [A]+"B|...\nsalt" hash the same bytes.
72func TestAppsDigestRejectsSaltHidingApps(t *testing.T) {
73	full := AppsDigest(apps2(), "salt")
74	defer func() {
75		if recover() == nil {
76			t.Error("expected panic for a salt with a newline")
77		}
78	}()
79	got := AppsDigest(apps2()[:1], "Beta|gno.land/r/x/beta|g1beta\nsalt")
80	if got == full {
81		t.Error("the same digest opens to a shorter application list")
82	}
83}