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.

registry_test.gno

35.21 Kb · 835 lines
  1package qrcregistry
  2
  3import (
  4	"chain/runtime"
  5	"crypto/bech32"
  6	"crypto/sha256"
  7	"encoding/base64"
  8	"encoding/hex"
  9	"strconv"
 10	"strings"
 11	"testing"
 12
 13	"gno.land/p/nt/testutils/v0"
 14	"gno.land/p/nt/uassert/v0"
 15	"gno.land/p/nym-rootlatch001/qrc/v1"
 16	"gno.land/p/nym-rootlatch001/qrcsigner/v1"
 17)
 18
 19const registryPath = "gno.land/r/nym-rootlatch001/qrcregistry/v1"
 20
 21// holder plays the owner of an account: it holds the one-time keys of one
 22// commit and signs requests with them, as a wallet would off-chain.
 23type holder struct {
 24	account address
 25	id      qrc.ID
 26	height  int
 27	kit     *qrcsigner.Kit
 28}
 29
 30// newHolder derives the commit number generation of account. The entropy
 31// depends on the account alone, so that every generation of an account comes
 32// from one secret, as it does in a wallet.
 33func newHolder(account address, generation uint32) *holder {
 34	return newHolderAt(account, generation, qrc.MinHeight)
 35}
 36
 37// newHolderAt is newHolder for trees of the given height.
 38func newHolderAt(account address, generation uint32, height int) *holder {
 39	entropy := sha256.Sum256([]byte("test entropy of " + account.String()))
 40	id := qrc.ID{
 41		ChainID:    runtime.ChainID(),
 42		Registry:   registryPath,
 43		Account:    account.String(),
 44		Generation: generation,
 45	}
 46	return &holder{account: account, id: id, height: height, kit: qrcsigner.New(entropy[:], id, height)}
 47}
 48
 49func (h *holder) roots() (rootSHA256, rootKeccak256 string) {
 50	a, b := h.kit.Roots()
 51	return hex.EncodeToString(a[:]), hex.EncodeToString(b[:])
 52}
 53
 54func (h *holder) signBind(leaf int, keyType string, key []byte) (proofSHA256, proofKeccak256 []byte) {
 55	return h.kit.Sign(leaf, qrc.BindMessage(h.id, uint32(leaf), keyType, key))
 56}
 57
 58func (h *holder) signRotate(leaf int, next *holder) (proofSHA256, proofKeccak256 []byte) {
 59	rootSHA256, rootKeccak256 := next.kit.Roots()
 60	return h.kit.Sign(leaf, qrc.RotateMessage(h.id, uint32(leaf), rootSHA256, rootKeccak256, next.height))
 61}
 62
 63func (h *holder) signAuthorize(leaf int, app string, payload []byte) (proofSHA256, proofKeccak256 []byte) {
 64	return h.kit.Sign(leaf, qrc.AuthorizeMessage(h.id, uint32(leaf), app, payload))
 65}
 66
 67// register registers h's commit. The test must have made h's account the
 68// caller beforehand: testing.SetRealm only acts on the function that calls
 69// it, so it cannot be called from here. The realm comes second because a
 70// function that takes it first is a crossing function.
 71func register(h *holder, rlm realm) {
 72	rootSHA256, rootKeccak256 := h.roots()
 73	Register(cross(rlm), rootSHA256, rootKeccak256, qrc.MinHeight)
 74}
 75
 76// tamper returns a copy of proof with one bit of its byte number at flipped.
 77func tamper(proof []byte, at int) []byte {
 78	changed := append([]byte(nil), proof...)
 79	changed[at] ^= 0x01
 80	return changed
 81}
 82
 83var (
 84	// relayer has nothing to do with any commit. Requests sent from it must
 85	// stand on the one-time keys alone.
 86	relayer = testing.NewUserRealm(testutils.TestAddress("relayer"))
 87
 88	testKey = []byte("these bytes stand for a public key of a scheme chosen after D-day")
 89)
 90
 91func TestRegister(cur realm, t *testing.T) {
 92	alice := testutils.TestAddress("reg-alice")
 93	h := newHolder(alice, 0)
 94	rootSHA256, rootKeccak256 := h.roots()
 95	zero := strings.Repeat("00", qrc.HashSize)
 96	accounts, withKey := Count()
 97
 98	uassert.False(t, Has(alice))
 99	uassert.Equal(t, "null", Lookup(alice))
100
101	// A realm cannot hold a commit, nor register one for the user calling it.
102	testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/app"))
103	uassert.AbortsContains(t, cur, "only a user account", func() {
104		Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight)
105	})
106
107	testing.SetRealm(testing.NewUserRealm(alice))
108	uassert.AbortsContains(t, cur, "64 hexadecimal characters", func() {
109		Register(cross(cur), rootSHA256[:62], rootKeccak256, qrc.MinHeight)
110	})
111	uassert.AbortsContains(t, cur, "64 hexadecimal characters", func() {
112		Register(cross(cur), rootSHA256, "zz"+rootKeccak256[2:], qrc.MinHeight)
113	})
114	uassert.AbortsContains(t, cur, "cannot be all zeros", func() {
115		Register(cross(cur), zero, rootKeccak256, qrc.MinHeight)
116	})
117	uassert.AbortsContains(t, cur, "cannot be all zeros", func() {
118		Register(cross(cur), rootSHA256, zero, qrc.MinHeight)
119	})
120	uassert.AbortsContains(t, cur, "two different trees", func() {
121		Register(cross(cur), rootSHA256, rootSHA256, qrc.MinHeight)
122	})
123	uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
124		Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight-1)
125	})
126	uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
127		Register(cross(cur), rootSHA256, rootKeccak256, qrc.MaxHeight+1)
128	})
129	uassert.False(t, Has(alice), "a rejected registration must leave nothing behind")
130
131	Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight)
132	uassert.True(t, Has(alice))
133	nowAccounts, nowWithKey := Count()
134	uassert.Equal(t, accounts+1, nowAccounts)
135	uassert.Equal(t, withKey, nowWithKey)
136	for leaf := 0; leaf < qrc.Leaves(qrc.MinHeight); leaf++ {
137		if IsUsed(alice, leaf) {
138			t.Fatalf("leaf %d is used right after registration", leaf)
139		}
140	}
141	if _, _, ok := Key(alice); ok {
142		t.Fatalf("a key is bound right after registration")
143	}
144	uassert.Equal(t, "", KeyBase64(alice))
145
146	// The usual key of the account has no say over the commit any more.
147	other := newHolder(alice, 1)
148	otherSHA256, otherKeccak256 := other.roots()
149	uassert.AbortsContains(t, cur, "already has a commit", func() {
150		Register(cross(cur), otherSHA256, otherKeccak256, qrc.MinHeight)
151	})
152	uassert.True(t, strings.Contains(Lookup(alice), `"rootSHA256":"`+rootSHA256+`"`))
153}
154
155func TestBind(cur realm, t *testing.T) {
156	alice := testutils.TestAddress("bind-alice")
157	mallory := testutils.TestAddress("bind-mallory")
158	h := newHolder(alice, 0)
159	testing.SetRealm(testing.NewUserRealm(alice))
160	register(h, cur)
161	_, withKey := Count()
162
163	proofSHA256, proofKeccak256 := h.signBind(3, "ML-DSA-65", testKey)
164
165	// Nothing here depends on who sends the transaction.
166	testing.SetRealm(relayer)
167
168	uassert.AbortsContains(t, cur, "no commit", func() {
169		Bind(cross(cur), mallory, 3, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
170	})
171	uassert.AbortsContains(t, cur, "leaf out of range", func() {
172		Bind(cross(cur), alice, 64, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
173	})
174	uassert.AbortsContains(t, cur, "leaf out of range", func() {
175		Bind(cross(cur), alice, -1, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
176	})
177	uassert.AbortsContains(t, cur, "key type", func() {
178		Bind(cross(cur), alice, 3, "", testKey, proofSHA256, proofKeccak256)
179	})
180	uassert.AbortsContains(t, cur, "key type", func() {
181		Bind(cross(cur), alice, 3, "ML DSA <65>", testKey, proofSHA256, proofKeccak256)
182	})
183	uassert.AbortsContains(t, cur, "key type", func() {
184		Bind(cross(cur), alice, 3, "-ML-DSA-65", testKey, proofSHA256, proofKeccak256)
185	})
186	uassert.AbortsContains(t, cur, "key type", func() {
187		Bind(cross(cur), alice, 3, strings.Repeat("k", MaxKeyTypeSize+1), testKey, proofSHA256, proofKeccak256)
188	})
189	uassert.AbortsContains(t, cur, "key must be between", func() {
190		Bind(cross(cur), alice, 3, "ML-DSA-65", nil, proofSHA256, proofKeccak256)
191	})
192	uassert.AbortsContains(t, cur, "key must be between", func() {
193		Bind(cross(cur), alice, 3, "ML-DSA-65", make([]byte, MaxKeySize+1), proofSHA256, proofKeccak256)
194	})
195
196	// A signature covers the leaf, the label and every byte of the key.
197	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
198		Bind(cross(cur), alice, 4, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
199	})
200	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
201		Bind(cross(cur), alice, 3, "ML-DSA-87", testKey, proofSHA256, proofKeccak256)
202	})
203	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
204		Bind(cross(cur), alice, 3, "ML-DSA-65", append([]byte("x"), testKey...), proofSHA256, proofKeccak256)
205	})
206	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
207		Bind(cross(cur), alice, 3, "ML-DSA-65", tamper(testKey, len(testKey)-1), proofSHA256, proofKeccak256)
208	})
209
210	// Both trees must agree: one valid proof is not enough.
211	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
212		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, tamper(proofSHA256, 0), proofKeccak256)
213	})
214	uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
215		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, tamper(proofKeccak256, 0))
216	})
217	uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
218		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, tamper(proofKeccak256, qrc.SignatureSize+5))
219	})
220	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
221		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofKeccak256, proofSHA256)
222	})
223	uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
224		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, proofSHA256)
225	})
226	uassert.AbortsContains(t, cur, "sha256 proof rejected: qrc: proof has the wrong size", func() {
227		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256[:len(proofSHA256)-1], proofKeccak256)
228	})
229	uassert.AbortsContains(t, cur, "keccak256 proof rejected: qrc: proof has the wrong size", func() {
230		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, nil)
231	})
232
233	// Keys of another account's commit are useless here.
234	stranger := newHolder(mallory, 0)
235	strangerSHA256, strangerKeccak256 := stranger.signBind(3, "ML-DSA-65", testKey)
236	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
237		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, strangerSHA256, strangerKeccak256)
238	})
239
240	// None of the rejected requests cost the account a one-time key.
241	for leaf := 0; leaf < qrc.Leaves(qrc.MinHeight); leaf++ {
242		if IsUsed(alice, leaf) {
243			t.Fatalf("leaf %d was burned by a rejected request", leaf)
244		}
245	}
246	if _, _, ok := Key(alice); ok {
247		t.Fatalf("a rejected request bound a key")
248	}
249
250	sent := append([]byte(nil), testKey...)
251	Bind(cross(cur), alice, 3, "ML-DSA-65", sent, proofSHA256, proofKeccak256)
252
253	keyType, got, ok := Key(alice)
254	uassert.True(t, ok)
255	uassert.Equal(t, "ML-DSA-65", keyType)
256	uassert.Equal(t, string(testKey), string(got))
257	uassert.Equal(t, base64.StdEncoding.EncodeToString(testKey), KeyBase64(alice))
258	uassert.True(t, IsUsed(alice, 3))
259	uassert.False(t, IsUsed(alice, 2))
260	uassert.False(t, IsUsed(alice, 4))
261	_, nowWithKey := Count()
262	uassert.Equal(t, withKey+1, nowWithKey)
263
264	// The stored key shares no memory with what came in or with what goes out.
265	sent[0] ^= 0xff
266	got[1] ^= 0xff
267	_, again, _ := Key(alice)
268	uassert.Equal(t, string(testKey), string(again))
269
270	// A one-time key signs once.
271	uassert.AbortsContains(t, cur, "already used", func() {
272		Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
273	})
274
275	// Binding again, with a fresh leaf, replaces the key.
276	second := []byte("a second public key")
277	secondSHA256, secondKeccak256 := h.signBind(63, "SLH-DSA-SHA2-128s", second)
278	Bind(cross(cur), alice, 63, "SLH-DSA-SHA2-128s", second, secondSHA256, secondKeccak256)
279	keyType, got, _ = Key(alice)
280	uassert.Equal(t, "SLH-DSA-SHA2-128s", keyType)
281	uassert.Equal(t, string(second), string(got))
282	uassert.True(t, IsUsed(alice, 63))
283	_, nowWithKey = Count()
284	uassert.Equal(t, withKey+1, nowWithKey, "an account counts once however many keys it bound")
285}
286
287func TestRotate(cur realm, t *testing.T) {
288	alice := testutils.TestAddress("rot-alice")
289	first := newHolder(alice, 0)
290	second := newHolder(alice, 1)
291	testing.SetRealm(testing.NewUserRealm(alice))
292	register(first, cur)
293	firstSHA256, firstKeccak256 := first.roots()
294	secondSHA256, secondKeccak256 := second.roots()
295
296	testing.SetRealm(relayer)
297
298	keySHA256, keyKeccak256 := first.signBind(0, "ML-DSA-65", testKey)
299	Bind(cross(cur), alice, 0, "ML-DSA-65", testKey, keySHA256, keyKeccak256)
300
301	proofSHA256, proofKeccak256 := first.signRotate(1, second)
302
303	// The signature covers both new roots and the height.
304	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
305		Rotate(cross(cur), alice, 1, secondKeccak256, secondSHA256, qrc.MinHeight, proofSHA256, proofKeccak256)
306	})
307	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
308		Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight+1, proofSHA256, proofKeccak256)
309	})
310	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
311		Rotate(cross(cur), alice, 2, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
312	})
313	uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
314		Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, tamper(proofKeccak256, 77))
315	})
316	uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
317		Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, 5, proofSHA256, proofKeccak256)
318	})
319	uassert.AbortsContains(t, cur, "two different trees", func() {
320		Rotate(cross(cur), alice, 1, secondSHA256, secondSHA256, qrc.MinHeight, proofSHA256, proofKeccak256)
321	})
322	uassert.AbortsContains(t, cur, "no commit", func() {
323		Rotate(cross(cur), testutils.TestAddress("rot-nobody"), 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
324	})
325	// A request to keep a current root is refused even when properly signed.
326	sameSHA256, sameKeccak256 := first.signRotate(1, first)
327	uassert.AbortsContains(t, cur, "never be registered again", func() {
328		Rotate(cross(cur), alice, 1, firstSHA256, firstKeccak256, qrc.MinHeight, sameSHA256, sameKeccak256)
329	})
330	uassert.False(t, IsUsed(alice, 1))
331
332	Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
333
334	lookup := Lookup(alice)
335	uassert.True(t, strings.Contains(lookup, `"generation":1`), lookup)
336	uassert.True(t, strings.Contains(lookup, `"rootSHA256":"`+secondSHA256+`"`), lookup)
337	uassert.True(t, strings.Contains(lookup, `"rootKeccak256":"`+secondKeccak256+`"`), lookup)
338	uassert.True(t, strings.Contains(lookup, `"usedCount":0`), lookup)
339	uassert.False(t, IsUsed(alice, 0), "the new trees start with every key unused")
340	uassert.False(t, IsUsed(alice, 1))
341
342	// The public key bound before the rotation stays.
343	keyType, got, ok := Key(alice)
344	uassert.True(t, ok)
345	uassert.Equal(t, "ML-DSA-65", keyType)
346	uassert.Equal(t, string(testKey), string(got))
347
348	// Every key of the replaced trees is void, used or not.
349	other := []byte("another public key")
350	oldSHA256, oldKeccak256 := first.signBind(2, "ML-DSA-65", other)
351	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
352		Bind(cross(cur), alice, 2, "ML-DSA-65", other, oldSHA256, oldKeccak256)
353	})
354	// Sending the rotation request a second time changes nothing.
355	uassert.AbortsContains(t, cur, "never be registered again", func() {
356		Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
357	})
358
359	// The new trees speak for the account from now on.
360	newSHA256, newKeccak256 := second.signBind(2, "ML-DSA-65", other)
361	Bind(cross(cur), alice, 2, "ML-DSA-65", other, newSHA256, newKeccak256)
362	_, got, _ = Key(alice)
363	uassert.Equal(t, string(other), string(got))
364
365	// A retired root never comes back, whichever of the two places it takes.
366	third := newHolder(alice, 2)
367	thirdSHA256, thirdKeccak256 := third.roots()
368	backSHA256, backKeccak256 := second.signRotate(3, first)
369	uassert.AbortsContains(t, cur, "never be registered again", func() {
370		Rotate(cross(cur), alice, 3, firstSHA256, firstKeccak256, qrc.MinHeight, backSHA256, backKeccak256)
371	})
372	uassert.AbortsContains(t, cur, "never be registered again", func() {
373		Rotate(cross(cur), alice, 3, thirdSHA256, firstSHA256, qrc.MinHeight, backSHA256, backKeccak256)
374	})
375	uassert.AbortsContains(t, cur, "never be registered again", func() {
376		Rotate(cross(cur), alice, 3, firstKeccak256, thirdKeccak256, qrc.MinHeight, backSHA256, backKeccak256)
377	})
378	uassert.False(t, IsUsed(alice, 3))
379
380	onSHA256, onKeccak256 := second.signRotate(3, third)
381	Rotate(cross(cur), alice, 3, thirdSHA256, thirdKeccak256, qrc.MinHeight, onSHA256, onKeccak256)
382	uassert.True(t, strings.Contains(Lookup(alice), `"generation":2`))
383}
384
385func TestAuthorize(cur realm, t *testing.T) {
386	const (
387		vault = "gno.land/r/someone/vault"
388		thief = "gno.land/r/someone/thief"
389	)
390	alice := testutils.TestAddress("auth-alice")
391	h := newHolder(alice, 0)
392	testing.SetRealm(testing.NewUserRealm(alice))
393	register(h, cur)
394	payload := []byte("withdraw 100ugnot to g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5")
395	proofSHA256, proofKeccak256 := h.signAuthorize(7, vault, payload)
396
397	// A user cannot spend a key through Authorize, whatever it is signed for.
398	testing.SetRealm(relayer)
399	uassert.AbortsContains(t, cur, "only a realm", func() {
400		Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
401	})
402	testing.SetRealm(testing.NewUserRealm(alice))
403	uassert.AbortsContains(t, cur, "only a realm", func() {
404		Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
405	})
406
407	// An approval given to one realm is useless to another.
408	testing.SetRealm(testing.NewCodeRealm(thief))
409	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
410		Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
411	})
412
413	testing.SetRealm(testing.NewCodeRealm(vault))
414	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
415		Authorize(cross(cur), alice, 7, []byte("withdraw 999ugnot"), proofSHA256, proofKeccak256)
416	})
417	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
418		Authorize(cross(cur), alice, 8, payload, proofSHA256, proofKeccak256)
419	})
420	uassert.AbortsContains(t, cur, "no commit", func() {
421		Authorize(cross(cur), testutils.TestAddress("auth-nobody"), 7, payload, proofSHA256, proofKeccak256)
422	})
423	uassert.False(t, IsUsed(alice, 7))
424
425	Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
426	uassert.True(t, IsUsed(alice, 7))
427	uassert.AbortsContains(t, cur, "already used", func() {
428		Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
429	})
430
431	// A proof made for Authorize cannot bind a key, and the reverse.
432	testing.SetRealm(relayer)
433	authSHA256, authKeccak256 := h.signAuthorize(9, vault, testKey)
434	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
435		Bind(cross(cur), alice, 9, vault, testKey, authSHA256, authKeccak256)
436	})
437	bindSHA256, bindKeccak256 := h.signBind(9, vault, testKey)
438	testing.SetRealm(testing.NewCodeRealm(vault))
439	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
440		Authorize(cross(cur), alice, 9, testKey, bindSHA256, bindKeccak256)
441	})
442	uassert.False(t, IsUsed(alice, 9))
443}
444
445// TestLatest registers more accounts than the home page lists and checks
446// that it shows the last ones, newest first. A registration only needs two
447// roots, so no key is derived here.
448func TestLatest(cur realm, t *testing.T) {
449	const count = latestKept + 2
450	accounts := make([]address, count)
451	before, _ := Count()
452	for i := range accounts {
453		accounts[i] = testutils.TestAddress("latest-" + string(rune('a'+i)))
454		rootSHA256 := sha256.Sum256([]byte("sha256 root of " + accounts[i].String()))
455		rootKeccak256 := sha256.Sum256([]byte("keccak256 root of " + accounts[i].String()))
456		testing.SetRealm(testing.NewUserRealm(accounts[i]))
457		Register(cross(cur), hex.EncodeToString(rootSHA256[:]), hex.EncodeToString(rootKeccak256[:]), qrc.MinHeight+i%3)
458	}
459	after, _ := Count()
460	uassert.Equal(t, before+count, after)
461	uassert.Equal(t, latestKept, len(latest))
462
463	home := Render("")
464	at := 0
465	for i := count - 1; i >= count-latestKept; i-- {
466		next := strings.Index(home[at:], accounts[i].String())
467		if next < 0 {
468			t.Fatalf("account %d is missing or out of order on the home page:\n%s", i, home)
469		}
470		at += next
471	}
472	for i := 0; i < count-latestKept; i++ {
473		uassert.False(t, strings.Contains(home, accounts[i].String()), "an account that left the list is still shown")
474		uassert.True(t, Has(accounts[i]), "an account that left the list lost its commit")
475	}
476	uassert.True(t, strings.Contains(home, "| "+strconv.Itoa(after)+" | "+accounts[count-1].String()+" | 0 of "), home)
477
478	// Latest lists the same accounts as the home page, in the same order, one
479	// JSON object each.
480	list := Latest()
481	uassert.True(t, strings.HasPrefix(list, "[{"), list)
482	uassert.True(t, strings.HasSuffix(list, "}]"), list)
483	uassert.Equal(t, latestKept, strings.Count(list, `{"account":`), list)
484	at = 0
485	for i := count - 1; i >= count-latestKept; i-- {
486		object := `{"account":"` + accounts[i].String() + `","rank":` + strconv.Itoa(before+i+1) +
487			`,"height":` + strconv.Itoa(qrc.MinHeight+i%3) + `,"usedCount":0,"generation":0}`
488		next := strings.Index(list[at:], object)
489		if next < 0 {
490			t.Fatalf("account %d is missing, wrong or out of order in Latest:\n%s", i, list)
491		}
492		at += next + len(object)
493	}
494	for i := 0; i < count-latestKept; i++ {
495		uassert.False(t, strings.Contains(list, accounts[i].String()), "an account that left the list is still in Latest")
496	}
497}
498
499func TestViews(cur realm, t *testing.T) {
500	alice := testutils.TestAddress("view-alice")
501	nobody := testutils.TestAddress("view-nobody")
502	h := newHolder(alice, 0)
503	rootSHA256, rootKeccak256 := h.roots()
504
505	uassert.True(t, strings.Contains(Render(nobody.String()), "**No commit.**"))
506	uassert.True(t, strings.Contains(Render("account?address="+nobody.String()), "**No commit.**"))
507
508	testing.SetRealm(testing.NewUserRealm(alice))
509	register(h, cur)
510	testing.SetRealm(relayer)
511
512	home := Render("")
513	uassert.True(t, strings.Contains(home, "# Quantum Recovery Commits"), home)
514	uassert.True(t, strings.Contains(home, alice.String()), home)
515	uassert.True(t, strings.Contains(home, " | "+alice.String()+" | 0 of 64 | none yet |"), home)
516
517	page := Render(alice.String())
518	uassert.True(t, strings.Contains(page, "**Recoverable.**"), page)
519	uassert.True(t, strings.Contains(page, rootSHA256), page)
520	uassert.True(t, strings.Contains(page, rootKeccak256), page)
521	uassert.True(t, strings.Contains(page, "| One-time keys | 64, 0 used |"), page)
522	uassert.True(t, strings.Contains(page, "| New public key | none yet |"), page)
523	uassert.Equal(t, page, Render("account?address="+alice.String()))
524
525	proofSHA256, proofKeccak256 := h.signBind(10, "ML-DSA-65", testKey)
526	Bind(cross(cur), alice, 10, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
527
528	digest := sha256.Sum256(testKey)
529	page = Render(alice.String())
530	uassert.True(t, strings.Contains(page, "| One-time keys | 64, 1 used |"), page)
531	uassert.True(t, strings.Contains(page, "`ML-DSA-65`, 65 bytes, SHA-256 `"+hex.EncodeToString(digest[:])+"`"), page)
532	uassert.True(t, strings.Contains(page, "with one-time key 10"), page)
533
534	// Leaf 10 is bit 2 of the second byte of the bitmap.
535	lookup := Lookup(alice)
536	uassert.True(t, strings.HasPrefix(lookup, `{"account":"`+alice.String()+`","rank":`), lookup)
537	uassert.True(t, strings.Contains(lookup, `"generation":0,"rotatedAt":0,"height":6,`), lookup)
538	uassert.True(t, strings.Contains(lookup, `"used":"0004000000000000","usedCount":1,`), lookup)
539	uassert.True(t, strings.Contains(lookup, `"keyType":"ML-DSA-65","keySize":65,"keySHA256":"`+hex.EncodeToString(digest[:])+`","keyLeaf":10,`), lookup)
540	uassert.True(t, strings.HasSuffix(lookup, `,"keyBinds":1}`), lookup)
541
542	// Latest gives the label of the bound key, and nothing about the key.
543	list := Latest()
544	uassert.True(t, strings.Contains(list, `"account":"`+alice.String()+`","rank":`), list)
545	uassert.True(t, strings.Contains(list, `,"height":6,"usedCount":1,"generation":0,"keyType":"ML-DSA-65"}`), list)
546	uassert.False(t, strings.Contains(list, hex.EncodeToString(digest[:])), list)
547
548	// Whatever the path holds, the page never repeats it unless it is an address.
549	for _, path := range []string{
550		"<script>alert(1)</script>",
551		"account?address=<script>alert(1)</script>",
552		"account",
553		"account?",
554		"g1notanaddress",
555		"[click](https://example.com)",
556		alice.String() + "/extra",
557	} {
558		page := Render(path)
559		uassert.True(t, strings.HasPrefix(page, "# Not an address"), path)
560		uassert.False(t, strings.Contains(page, "script"), path)
561		uassert.False(t, strings.Contains(page, "example.com"), path)
562	}
563}
564
565// bech32mOf returns account with the bech32m checksum in place of the bech32
566// one: the same 20 bytes, which the chain reads as the same account.
567func bech32mOf(account address) address {
568	hrp, data, err := bech32.Decode(account.String())
569	if err != nil {
570		panic(err)
571	}
572	spelled, err := bech32.EncodeM(hrp, data)
573	if err != nil {
574		panic(err)
575	}
576	return address(spelled)
577}
578
579// TestSpellings writes an address in capitals, as a QR code does, and with
580// the bech32m checksum. The chain reads all four spellings as one account, so
581// Bind, Rotate and the views must as well, while Authorize takes only the
582// spelling the chain writes, so that the calling realm holds the account that
583// signed. What is signed always names the account in lower case.
584func TestSpellings(cur realm, t *testing.T) {
585	const vault = "gno.land/r/someone/vault"
586	alice := testutils.TestAddress("caps-alice")
587	loud := address(strings.ToUpper(alice.String()))
588	quiet := bech32mOf(alice)
589	loudQuiet := address(strings.ToUpper(quiet.String()))
590	others := []address{loud, quiet, loudQuiet}
591	spellings := []address{alice, loud, quiet, loudQuiet}
592	mixed := address(strings.ToUpper(alice.String()[:20]) + alice.String()[20:])
593	for _, s := range spellings {
594		uassert.True(t, s.IsValid(), "the chain takes "+s.String())
595		uassert.Equal(t, alice.String(), canonical(s).String(), s.String())
596	}
597	uassert.False(t, mixed.IsValid(), "the chain refuses an address in mixed case")
598	uassert.Equal(t, mixed.String(), canonical(mixed).String())
599	uassert.Equal(t, "", canonical(address("")).String())
600	uassert.Equal(t, "1234", canonical(address("1234")).String())
601	uassert.Equal(t, "<script>", canonical(address("<script>")).String())
602
603	first := newHolder(alice, 0)
604	second := newHolder(alice, 1)
605	testing.SetRealm(testing.NewUserRealm(alice))
606	register(first, cur)
607	testing.SetRealm(relayer)
608
609	for _, s := range spellings {
610		uassert.True(t, Has(s), s.String())
611		uassert.Equal(t, Lookup(alice), Lookup(s), s.String())
612		uassert.Equal(t, Render(alice.String()), Render(s.String()), s.String())
613		uassert.Equal(t, Render(alice.String()), Render("account?address="+s.String()), s.String())
614	}
615	for _, s := range others {
616		uassert.False(t, strings.Contains(Render(s.String()), s.String()), "the page shows the address as the chain writes it")
617	}
618	uassert.False(t, Has(mixed))
619	uassert.Equal(t, "null", Lookup(mixed))
620	uassert.True(t, strings.HasPrefix(Render(mixed.String()), "# Not an address"))
621
622	// Bind: the proofs are those of the lower-case account.
623	bindSHA256, bindKeccak256 := first.signBind(5, "ML-DSA-65", testKey)
624	uassert.AbortsContains(t, cur, "no commit", func() {
625		Bind(cross(cur), mixed, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
626	})
627	uassert.False(t, IsUsed(loudQuiet, 5))
628	Bind(cross(cur), loudQuiet, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
629	for _, s := range spellings {
630		uassert.True(t, IsUsed(s, 5), s.String())
631	}
632	uassert.False(t, IsUsed(mixed, 5))
633	keyType, key, ok := Key(loud)
634	uassert.True(t, ok)
635	uassert.Equal(t, "ML-DSA-65", keyType)
636	uassert.Equal(t, string(testKey), string(key))
637	uassert.Equal(t, base64.StdEncoding.EncodeToString(testKey), KeyBase64(quiet))
638	uassert.Equal(t, "", KeyBase64(mixed))
639	uassert.AbortsContains(t, cur, "already used", func() {
640		Bind(cross(cur), alice, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
641	})
642
643	// Authorize takes the spelling the chain writes and no other.
644	payload := []byte("withdraw 100ugnot")
645	authSHA256, authKeccak256 := first.signAuthorize(6, vault, payload)
646	testing.SetRealm(testing.NewCodeRealm(vault))
647	for _, s := range others {
648		spelled := s
649		uassert.AbortsContains(t, cur, "lower-case bech32", func() {
650			Authorize(cross(cur), spelled, 6, payload, authSHA256, authKeccak256)
651		})
652	}
653	uassert.False(t, IsUsed(alice, 6))
654	Authorize(cross(cur), alice, 6, payload, authSHA256, authKeccak256)
655	uassert.True(t, IsUsed(alice, 6))
656
657	// Rotate.
658	testing.SetRealm(relayer)
659	secondSHA256, secondKeccak256 := second.roots()
660	rotSHA256, rotKeccak256 := first.signRotate(7, second)
661	Rotate(cross(cur), quiet, 7, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
662	lookup := Lookup(loud)
663	uassert.True(t, strings.HasPrefix(lookup, `{"account":"`+alice.String()+`","rank":`), lookup)
664	uassert.True(t, strings.Contains(lookup, `"generation":1,`), lookup)
665	uassert.True(t, strings.Contains(lookup, `"rootSHA256":"`+secondSHA256+`"`), lookup)
666	uassert.True(t, strings.Contains(lookup, `"usedCount":0,`), lookup)
667}
668
669// TestSpentCommit spends every key of a commit: the page stops calling the
670// account recoverable, and nothing can replace the commit any more.
671func TestSpentCommit(cur realm, t *testing.T) {
672	const vault = "gno.land/r/someone/vault"
673	alice := testutils.TestAddress("spent-alice")
674	first := newHolder(alice, 0)
675	testing.SetRealm(testing.NewUserRealm(alice))
676	register(first, cur)
677
678	testing.SetRealm(testing.NewCodeRealm(vault))
679	last := qrc.Leaves(qrc.MinHeight) - 1
680	for leaf := 0; leaf < last; leaf++ {
681		payload := []byte("approval " + strconv.Itoa(leaf))
682		a, b := first.signAuthorize(leaf, vault, payload)
683		Authorize(cross(cur), alice, leaf, payload, a, b)
684	}
685	page := Render(alice.String())
686	uassert.True(t, strings.Contains(page, "**Recoverable.**"), page)
687	uassert.True(t, strings.Contains(page, "| One-time keys | 64, 63 used |"), page)
688
689	payload := []byte("the last approval")
690	a, b := first.signAuthorize(last, vault, payload)
691	Authorize(cross(cur), alice, last, payload, a, b)
692	page = Render(alice.String())
693	uassert.False(t, strings.Contains(page, "Recoverable"), page)
694	uassert.True(t, strings.HasPrefix(page, "# "+alice.String()+"\n\n**No one-time key left.**"), page)
695	uassert.True(t, strings.Contains(page, "| One-time keys | 64, 64 used |"), page)
696
697	testing.SetRealm(relayer)
698	second := newHolder(alice, 1)
699	secondSHA256, secondKeccak256 := second.roots()
700	rotSHA256, rotKeccak256 := first.signRotate(last, second)
701	uassert.AbortsContains(t, cur, "already used", func() {
702		Rotate(cross(cur), alice, last, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
703	})
704}
705
706// TestKeyGeneration binds in one generation, rotates and binds again: a leaf
707// number only means something with the generation it belongs to.
708func TestKeyGeneration(cur realm, t *testing.T) {
709	alice := testutils.TestAddress("keygen-alice")
710	first := newHolder(alice, 0)
711	second := newHolder(alice, 1)
712	testing.SetRealm(testing.NewUserRealm(alice))
713	register(first, cur)
714	testing.SetRealm(relayer)
715
716	bindSHA256, bindKeccak256 := first.signBind(10, "ML-DSA-65", testKey)
717	Bind(cross(cur), alice, 10, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
718	secondSHA256, secondKeccak256 := second.roots()
719	rotSHA256, rotKeccak256 := first.signRotate(11, second)
720	Rotate(cross(cur), alice, 11, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
721
722	lookup := Lookup(alice)
723	uassert.True(t, strings.Contains(lookup, `"generation":1,`), lookup)
724	uassert.True(t, strings.Contains(lookup, `"keyLeaf":10,"keyGeneration":0,`), lookup)
725	page := Render(alice.String())
726	uassert.True(t, strings.Contains(page, "with one-time key 10 of generation 0 |"), page)
727	uassert.False(t, IsUsed(alice, 10), "leaf 10 of the new trees is unspent")
728
729	other := []byte("a key bound in the second generation")
730	againSHA256, againKeccak256 := second.signBind(10, "ML-DSA-65", other)
731	Bind(cross(cur), alice, 10, "ML-DSA-65", other, againSHA256, againKeccak256)
732	lookup = Lookup(alice)
733	uassert.True(t, strings.Contains(lookup, `"keyLeaf":10,"keyGeneration":1,`), lookup)
734	uassert.True(t, strings.HasSuffix(lookup, `,"keyBinds":2}`), lookup)
735}
736
737// TestSpaces: gnoweb sends a space typed around the address in the form as
738// '+', which the page ignores.
739func TestSpaces(cur realm, t *testing.T) {
740	alice := testutils.TestAddress("spaces-alice")
741	page := Render(alice.String())
742	for _, path := range []string{
743		"account?address=+" + alice.String(),
744		"account?address=" + alice.String() + "+",
745		"account?address=++" + alice.String() + "++",
746	} {
747		uassert.Equal(t, page, Render(path), path)
748	}
749}
750
751// TestStaleRequest pins down what the documentation of Bind says: a signed
752// request stays valid until its leaf is spent or the account rotates, and
753// requests take effect in the order they land, not the order they were
754// signed.
755func TestStaleRequest(cur realm, t *testing.T) {
756	alice := testutils.TestAddress("stale-alice")
757	first := newHolder(alice, 0)
758	second := newHolder(alice, 1)
759	testing.SetRealm(testing.NewUserRealm(alice))
760	register(first, cur)
761	testing.SetRealm(relayer)
762
763	earlier := []byte("the key alice signed for first")
764	later := []byte("the key alice signed for next")
765	earlierSHA256, earlierKeccak256 := first.signBind(1, "ML-DSA-65", earlier)
766	laterSHA256, laterKeccak256 := first.signBind(2, "ML-DSA-65", later)
767	Bind(cross(cur), alice, 2, "ML-DSA-65", later, laterSHA256, laterKeccak256)
768	Bind(cross(cur), alice, 1, "ML-DSA-65", earlier, earlierSHA256, earlierKeccak256)
769	_, key, _ := Key(alice)
770	uassert.Equal(t, string(earlier), string(key), "the request that lands last wins")
771
772	// A rotation is what retires a request still pending.
773	pendingSHA256, pendingKeccak256 := first.signBind(3, "ML-DSA-65", earlier)
774	secondSHA256, secondKeccak256 := second.roots()
775	rotSHA256, rotKeccak256 := first.signRotate(4, second)
776	Rotate(cross(cur), alice, 4, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
777	uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
778		Bind(cross(cur), alice, 3, "ML-DSA-65", earlier, pendingSHA256, pendingKeccak256)
779	})
780}
781
782// TestRotateAcrossHeights moves a commit to a taller tree and back.
783func TestRotateAcrossHeights(cur realm, t *testing.T) {
784	alice := testutils.TestAddress("heights-alice")
785	first := newHolder(alice, 0)
786	second := newHolderAt(alice, 1, qrc.MinHeight+1)
787	third := newHolder(alice, 2)
788	testing.SetRealm(testing.NewUserRealm(alice))
789	register(first, cur)
790	testing.SetRealm(relayer)
791
792	secondSHA256, secondKeccak256 := second.roots()
793	toSecondSHA256, toSecondKeccak256 := first.signRotate(5, second)
794	Rotate(cross(cur), alice, 5, secondSHA256, secondKeccak256, qrc.MinHeight+1, toSecondSHA256, toSecondKeccak256)
795	lookup := Lookup(alice)
796	uassert.True(t, strings.Contains(lookup, `"height":7,`), lookup)
797	uassert.True(t, strings.HasSuffix(lookup, `,"used":"`+strings.Repeat("00", 16)+`","usedCount":0}`), lookup)
798
799	// A leaf only the taller tree has.
800	bindSHA256, bindKeccak256 := second.signBind(100, "ML-DSA-65", testKey)
801	Bind(cross(cur), alice, 100, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
802	uassert.True(t, IsUsed(alice, 100))
803
804	thirdSHA256, thirdKeccak256 := third.roots()
805	toThirdSHA256, toThirdKeccak256 := second.signRotate(127, third)
806	Rotate(cross(cur), alice, 127, thirdSHA256, thirdKeccak256, qrc.MinHeight, toThirdSHA256, toThirdKeccak256)
807	lookup = Lookup(alice)
808	uassert.True(t, strings.Contains(lookup, `"generation":2,`), lookup)
809	uassert.True(t, strings.Contains(lookup, `"height":6,`), lookup)
810	uassert.True(t, strings.Contains(lookup, `"used":"`+strings.Repeat("00", 8)+`","usedCount":0,`), lookup)
811	uassert.True(t, strings.Contains(lookup, `"keyLeaf":100,"keyGeneration":1,`), lookup)
812	uassert.False(t, IsUsed(alice, 100), "leaf 100 is out of range again")
813}
814
815// TestLargest binds the largest key and the longest label Bind takes.
816func TestLargest(cur realm, t *testing.T) {
817	alice := testutils.TestAddress("largest-alice")
818	h := newHolder(alice, 0)
819	testing.SetRealm(testing.NewUserRealm(alice))
820	register(h, cur)
821	testing.SetRealm(relayer)
822
823	key := make([]byte, MaxKeySize)
824	for i := range key {
825		key[i] = byte(i)
826	}
827	label := "K" + strings.Repeat("k", MaxKeyTypeSize-1)
828	proofSHA256, proofKeccak256 := h.signBind(0, label, key)
829	Bind(cross(cur), alice, 0, label, key, proofSHA256, proofKeccak256)
830	keyType, bound, ok := Key(alice)
831	uassert.True(t, ok)
832	uassert.Equal(t, label, keyType)
833	uassert.Equal(t, MaxKeySize, len(bound))
834	uassert.True(t, strings.Contains(Lookup(alice), `"keySize":65536,`))
835}