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.

signer_test.gno

9.59 Kb · 266 lines
  1package qrcsigner
  2
  3import (
  4	"crypto/keccak256"
  5	"crypto/sha256"
  6	"encoding/hex"
  7	"testing"
  8
  9	"gno.land/p/nym-rootlatch001/qrc/v1"
 10)
 11
 12// The commit of the first test vector (see vectors/v1.json).
 13var testID = qrc.ID{
 14	ChainID:    "dev",
 15	Registry:   "gno.land/r/nym-rootlatch001/qrcregistry/v1",
 16	Account:    "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
 17	Generation: 0,
 18}
 19
 20func testEntropy() []byte {
 21	entropy := make([]byte, EntropySize)
 22	for i := range entropy {
 23		entropy[i] = byte(i)
 24	}
 25	return entropy
 26}
 27
 28func hexOf(b [qrc.HashSize]byte) string { return hex.EncodeToString(b[:]) }
 29
 30// TestVector checks this implementation against the first test vector, which
 31// the Go build of this same code wrote and which the TypeScript library is
 32// tested against: three runtimes, one result.
 33func TestVector(t *testing.T) {
 34	kit := New(testEntropy(), testID, qrc.MinHeight)
 35	rootSHA256, rootKeccak256 := kit.Roots()
 36	if got := hexOf(rootSHA256); got != "7d5cd56c59431c38474c804eef1069aa4b2bd10209ff415c5aaef9becc126d6c" {
 37		t.Errorf("sha256 root = %s", got)
 38	}
 39	if got := hexOf(rootKeccak256); got != "eb2fd77bc5e8be3069f1269629c008abe17c0eed9d56a128c4dd0f451e359ed3" {
 40		t.Errorf("keccak256 root = %s", got)
 41	}
 42
 43	key, _ := hex.DecodeString("96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7b413f47d13ee2fe6c845b2ee141af81d")
 44	msg := qrc.BindMessage(testID, 0, "ML-DSA-65", key)
 45	proofSHA256, proofKeccak256 := kit.Sign(0, msg)
 46	if got := hexOf(sha256.Sum256(proofSHA256)); got != "5230669750006c8d68817925d27db1e9c865fee2f54372b3661e57e0aa04b93c" {
 47		t.Errorf("sha256 of the sha256 proof = %s", got)
 48	}
 49	if got := hexOf(sha256.Sum256(proofKeccak256)); got != "06b65a004eb7ed29ee594da58893ea78281a845d6874004d155f4d06b240042e" {
 50		t.Errorf("sha256 of the keccak256 proof = %s", got)
 51	}
 52	if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, 0, msg, proofSHA256); err != nil {
 53		t.Errorf("sha256: %v", err)
 54	}
 55	if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, 0, msg, proofKeccak256); err != nil {
 56		t.Errorf("keccak256: %v", err)
 57	}
 58}
 59
 60func TestSignVerify(t *testing.T) {
 61	kit := New(testEntropy(), testID, qrc.MinHeight)
 62	rootSHA256, rootKeccak256 := kit.Roots()
 63	if rootSHA256 == rootKeccak256 {
 64		t.Fatalf("the two commits are equal")
 65	}
 66
 67	for _, leaf := range []int{0, 1, 42, 63} {
 68		msg := qrc.BindMessage(testID, uint32(leaf), "ML-DSA-65", []byte("public key bytes"))
 69		proofSHA256, proofKeccak256 := kit.Sign(leaf, msg)
 70		if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, leaf, msg, proofSHA256); err != nil {
 71			t.Fatalf("sha256, leaf %d: %v", leaf, err)
 72		}
 73		if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, leaf, msg, proofKeccak256); err != nil {
 74			t.Fatalf("keccak256, leaf %d: %v", leaf, err)
 75		}
 76
 77		// A proof is good for its own tree, leaf and message only.
 78		if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, leaf, msg, proofSHA256); err != qrc.ErrMismatch {
 79			t.Fatalf("leaf %d: sha256 proof against the keccak256 commit: %v", leaf, err)
 80		}
 81		if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, leaf^1, msg, proofSHA256); err != qrc.ErrMismatch {
 82			t.Fatalf("leaf %d: proof accepted for its neighbour: %v", leaf, err)
 83		}
 84	}
 85}
 86
 87// hmacSHA256 is HMAC as RFC 2104 writes it, for a key of at most 64 bytes.
 88func hmacSHA256(key, msg []byte) [qrc.HashSize]byte {
 89	inner := make([]byte, 64, 64+len(msg))
 90	outer := make([]byte, 64, 64+qrc.HashSize)
 91	copy(inner, key)
 92	copy(outer, key)
 93	for i := 0; i < 64; i++ {
 94		inner[i] ^= 0x36
 95		outer[i] ^= 0x5c
 96	}
 97	digest := sha256.Sum256(append(inner, msg...))
 98	return sha256.Sum256(append(outer, digest[:]...))
 99}
100
101// TestDerivation recomputes secrets from the formulas of the package
102// documentation, written out the long way, and compares them with what the
103// trees use.
104func TestDerivation(t *testing.T) {
105	entropy := testEntropy()
106
107	// RFC 4231, test case 2: the HMAC of this test is the standard one.
108	if got := hexOf(hmacSHA256([]byte("Jefe"), []byte("what do ya want for nothing?"))); got != "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" {
109		t.Fatalf("HMAC-SHA256 test case = %s", got)
110	}
111
112	seedSHA256 := keccak256.Sum256(append([]byte("QuantumRecoveryCommit/v1/seed/sha256\x00"), entropy...))
113	seedKeccak256 := sha256.Sum256(append([]byte("QuantumRecoveryCommit/v1/seed/keccak256\x00"), entropy...))
114	if seedSHA256 != treeSeed(qrc.SHA256, entropy) || seedKeccak256 != treeSeed(qrc.Keccak256, entropy) {
115		t.Fatalf("tree seeds differ from their definition")
116	}
117
118	treeSHA256 := NewTree(qrc.SHA256, entropy, testID, qrc.MinHeight)
119	treeKeccak256 := NewTree(qrc.Keccak256, entropy, testID, qrc.MinHeight)
120	for _, tc := range []struct{ leaf, bit, side int }{
121		{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0, 0},
122		{63, 255, 1}, {37, 128, 0}, {5, 255, 0}, {62, 7, 1},
123	} {
124		info := append([]byte("QuantumRecoveryCommit/v1/secret\x00"), testID.Bytes()...)
125		info = append(info,
126			byte(tc.leaf>>24), byte(tc.leaf>>16), byte(tc.leaf>>8), byte(tc.leaf),
127			byte(tc.bit>>8), byte(tc.bit),
128			byte(tc.side))
129
130		if want := hmacSHA256(seedSHA256[:], info); treeSHA256.secret(tc.leaf, tc.bit, tc.side) != want {
131			t.Errorf("sha256 secret (%d, %d, %d) differs from its definition", tc.leaf, tc.bit, tc.side)
132		}
133		if want := keccak256.Sum256(append(seedKeccak256[:], info...)); treeKeccak256.secret(tc.leaf, tc.bit, tc.side) != want {
134			t.Errorf("keccak256 secret (%d, %d, %d) differs from its definition", tc.leaf, tc.bit, tc.side)
135		}
136	}
137}
138
139// TestProofLayout checks a proof against the description of package qrc:
140// in every pair, the secret on the side the digest bit selects and the hash
141// of the other secret, then the siblings up to the root.
142func TestProofLayout(t *testing.T) {
143	const leaf = 21
144	msg := []byte("a message")
145	for _, h := range []qrc.Hash{qrc.SHA256, qrc.Keccak256} {
146		tree := NewTree(h, testEntropy(), testID, qrc.MinHeight)
147		if tree.Hash() != h || tree.Height() != qrc.MinHeight {
148			t.Fatalf("%s: tree reports %s, height %d", h, tree.Hash(), tree.Height())
149		}
150		proof := tree.Sign(leaf, msg)
151		if len(proof) != qrc.ProofSize(qrc.MinHeight) {
152			t.Fatalf("%s: proof of %d bytes", h, len(proof))
153		}
154
155		digest := h.Sum(msg)
156		zeros, ones := 0, 0
157		for bit := 0; bit < qrc.DigestBits; bit++ {
158			selected := int(digest[bit/8]>>(7-uint(bit%8))) & 1
159			if selected == 0 {
160				zeros++
161			} else {
162				ones++
163			}
164			for side := 0; side < 2; side++ {
165				want := tree.secret(leaf, bit, side)
166				if side != selected {
167					want = h.Sum(want[:])
168				}
169				at := (2*bit + side) * qrc.HashSize
170				if string(proof[at:at+qrc.HashSize]) != string(want[:]) {
171					t.Fatalf("%s: bit %d, side %d holds the wrong value", h, bit, side)
172				}
173			}
174		}
175		if zeros == 0 || ones == 0 {
176			t.Fatalf("%s: the digest has a single bit value, pick another message", h)
177		}
178
179		// The path: leaf 21 is 010101 in binary, so its siblings sit to the
180		// left, right, left, right, left, right of the nodes on the way up.
181		node := leaf
182		for level := 0; level < qrc.MinHeight; level++ {
183			sibling := node ^ 1
184			want := tree.levels[level][sibling*qrc.HashSize : (sibling+1)*qrc.HashSize]
185			at := qrc.SignatureSize + level*qrc.HashSize
186			if string(proof[at:at+qrc.HashSize]) != string(want) {
187				t.Fatalf("%s: wrong sibling at level %d", h, level)
188			}
189			node >>= 1
190		}
191	}
192}
193
194// TestCommitsAreSeparate checks that nothing but the same entropy and the
195// same commit ID leads to the same keys.
196func TestCommitsAreSeparate(t *testing.T) {
197	base := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight).Root()
198	if again := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight).Root(); again != base {
199		t.Fatalf("the same entropy and ID gave two different commits")
200	}
201
202	seen := map[string]string{hexOf(base): "base"}
203	check := func(name string, entropy []byte, id qrc.ID) {
204		root := hexOf(NewTree(qrc.SHA256, entropy, id, qrc.MinHeight).Root())
205		if other, ok := seen[root]; ok {
206			t.Errorf("%s and %s have the same commit", name, other)
207		}
208		seen[root] = name
209	}
210
211	entropy := testEntropy()
212	entropy[31] ^= 1
213	check("another entropy", entropy, testID)
214
215	id := testID
216	id.ChainID = "onyx-1"
217	check("another chain", testEntropy(), id)
218	id = testID
219	id.Registry = "gno.land/r/other/qrcregistry/v1"
220	check("another registry", testEntropy(), id)
221	id = testID
222	id.Account = "g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj"
223	check("another account", testEntropy(), id)
224	id = testID
225	id.Generation = 1
226	check("another generation", testEntropy(), id)
227
228	// The two trees of one commit share no secret either.
229	a := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight)
230	b := NewTree(qrc.Keccak256, testEntropy(), testID, qrc.MinHeight)
231	if a.secret(0, 0, 0) == b.secret(0, 0, 0) {
232		t.Errorf("the two trees share a secret")
233	}
234}
235
236func TestBadArguments(t *testing.T) {
237	for name, f := range map[string]func(){
238		"unknown hash":  func() { NewTree(qrc.Hash(9), testEntropy(), testID, qrc.MinHeight) },
239		"short entropy": func() { NewTree(qrc.SHA256, testEntropy()[:31], testID, qrc.MinHeight) },
240		"long entropy":  func() { NewTree(qrc.SHA256, append(testEntropy(), 0), testID, qrc.MinHeight) },
241		"no entropy":    func() { NewTree(qrc.SHA256, nil, testID, qrc.MinHeight) },
242		"height 5":      func() { NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight-1) },
243		"height 17":     func() { NewTree(qrc.SHA256, testEntropy(), testID, qrc.MaxHeight+1) },
244	} {
245		if !panics(f) {
246			t.Errorf("%s: accepted", name)
247		}
248	}
249
250	tree := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight)
251	for _, leaf := range []int{-1, 64, 1 << 20} {
252		if !panics(func() { tree.Sign(leaf, []byte("m")) }) {
253			t.Errorf("leaf %d: signed", leaf)
254		}
255	}
256}
257
258func panics(f func()) (panicked bool) {
259	defer func() {
260		if recover() != nil {
261			panicked = true
262		}
263	}()
264	f()
265	return false
266}