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.gno

15.82 Kb · 432 lines
  1// Package qrcregistry keeps the Quantum Recovery Commit of user accounts.
  2//
  3// A commit is a pair of Merkle roots, each standing for at least 64 Lamport
  4// one-time keys, one tree hashed with SHA-256 and the other with Keccak-256
  5// (see package qrc). An account registers its commit once, with an ordinary
  6// transaction, while its usual key can still be trusted. From then on the
  7// one-time keys, and nothing else, can speak for the account in this realm:
  8//
  9//   - Bind registers new public key bytes of any kind for the account,
 10//   - Rotate replaces the commit before its keys run out,
 11//   - Authorize lets another realm spend a key on a request of its own.
 12//
 13// Bind and Rotate are open to any sender, and Authorize to any realm, for
 14// approvals made out to that realm's package path. What they check is a pair
 15// of hash-based signatures, one per tree, never who signed the transaction.
 16// An account whose usual key has been broken can therefore still name a new
 17// public key here, and whoever broke that key cannot touch the commit. This
 18// realm only records that key: for it to sign for the account would take a
 19// change to the chain.
 20//
 21// Each one-time key signs once. Once every key of a commit is spent, the
 22// account can never bind, rotate or authorize again here, and the key bound
 23// last stays for good, so a wallet keeps the last key of a commit for a
 24// rotation. A commit is never deleted: what it stores keeps its storage
 25// deposit.
 26//
 27// The realm has no owner, no administrator and no parameter that can change
 28// after deployment.
 29package qrcregistry
 30
 31import (
 32	"chain"
 33	"chain/runtime"
 34	"crypto/bech32"
 35	"crypto/sha256"
 36	"encoding/hex"
 37	"strconv"
 38	"time"
 39
 40	"gno.land/p/nt/avl/v0"
 41	"gno.land/p/nym-rootlatch001/qrc/v1"
 42)
 43
 44const (
 45	// MaxKeySize is the largest public key, in bytes, Bind accepts. It is 25
 46	// times the largest signature public key standardized so far
 47	// (ML-DSA-87, 2592 bytes).
 48	MaxKeySize = 1 << 16
 49
 50	// MaxKeyTypeSize is the longest key type label, in bytes, Bind accepts.
 51	MaxKeyTypeSize = 64
 52)
 53
 54// commit is everything the registry knows about one account.
 55type commit struct {
 56	rootSHA256    [qrc.HashSize]byte
 57	rootKeccak256 [qrc.HashSize]byte
 58	height        int
 59	generation    uint32 // number of rotations so far
 60
 61	used      []byte // one bit per leaf of the current trees, set once spent
 62	usedCount int
 63	retired   []byte // both roots of every earlier generation, 64 bytes each
 64
 65	rank           int   // 1 for the first account that registered
 66	registeredAt   int64 // block height of the registration
 67	registeredTime int64 // block time of the registration, Unix seconds
 68	rotatedAt      int64 // block height of the last rotation, 0 if none
 69
 70	keyType       string // label of the public key last bound, "" if none
 71	key           []byte
 72	keyLeaf       int    // leaf that signed for the key
 73	keyGeneration uint32 // generation of the trees keyLeaf belongs to
 74	keyAt         int64  // block height at which the key was bound
 75	keyBinds      int    // number of keys bound so far
 76}
 77
 78// latestKept is the number of accounts the home page lists.
 79const latestKept = 10
 80
 81var (
 82	commits avl.Tree // address -> *commit
 83	bound   int      // number of accounts with a bound key
 84
 85	// latest holds the accounts that registered last, newest first, at most
 86	// latestKept of them. It is all the home page needs, and unlike an index
 87	// of every registration it costs a new account nothing to keep. The full
 88	// history is in the Registered events.
 89	latest []string
 90)
 91
 92// Register stores the Quantum Recovery Commit of the calling account: the
 93// roots of its SHA-256 and Keccak-256 trees, hex encoded, and their height.
 94//
 95// An account registers once. Its usual key has no say over the commit
 96// afterwards; only the one-time keys can replace it, through Rotate.
 97//
 98// A registration can never be corrected or withdrawn, and nothing here
 99// checks that the roots are a SHA-256 tree and a Keccak-256 tree of the
100// given height: derive both roots and the height from the kit, in this
101// order, and check them before sending. The caller must be the account
102// itself, in a direct call or in a script it runs; a session key is refused.
103func Register(cur realm, rootSHA256, rootKeccak256 string, height int) {
104	// cur belongs to this very call: the runtime makes it on the way in, so
105	// it needs no IsCurrent check, and its Previous is whoever called.
106	caller := cur.Previous()
107	if !caller.IsUser() {
108		panic("only a user account can register a commit")
109	}
110	if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
111		panic("a commit must be registered with the account's own key, not a session key")
112	}
113	account := caller.Address().String()
114	if commits.Has(account) {
115		panic("this account already has a commit: only its one-time keys can replace it")
116	}
117
118	c := &commit{
119		rootSHA256:     decodeRoot(rootSHA256),
120		rootKeccak256:  decodeRoot(rootKeccak256),
121		height:         height,
122		rank:           commits.Size() + 1,
123		registeredAt:   runtime.ChainHeight(),
124		registeredTime: time.Now().Unix(),
125	}
126	checkTrees(c.rootSHA256, c.rootKeccak256, height)
127	c.used = make([]byte, qrc.Leaves(height)/8)
128
129	commits.Set(account, c)
130	if len(latest) < latestKept {
131		latest = append(latest, "")
132	}
133	for i := len(latest) - 1; i > 0; i-- {
134		latest[i] = latest[i-1]
135	}
136	latest[0] = account
137
138	chain.Emit("Registered",
139		"account", account,
140		"rootSHA256", hex.EncodeToString(c.rootSHA256[:]),
141		"rootKeccak256", hex.EncodeToString(c.rootKeccak256[:]),
142		"height", strconv.Itoa(height),
143		"rank", strconv.Itoa(c.rank),
144	)
145}
146
147// Bind registers key as the new public key of account, under the free label
148// keyType (for instance "ML-DSA-65"). key holds 1 to MaxKeySize bytes; a
149// scheme with a longer public key can bind a digest of it, under a label
150// that says so.
151//
152// The request must be signed with one-time key number leaf of both trees of
153// the account: proofSHA256 and proofKeccak256 are the proofs of
154// qrc.BindMessage for these arguments, with the account written as the chain
155// writes it (lower case), whatever spelling the account argument uses. The
156// leaf is spent.
157//
158// A signed request stays valid until its leaf is spent or the account
159// rotates, and whoever holds it may send it at any time: requests take
160// effect in the order they land, not the order they were signed. To replace
161// a key while an earlier Bind for another key may still be pending, rotate
162// first, bind in the new generation, then check Key. After a failure, send
163// the same signed request again rather than sign for another key.
164//
165// Anyone may send the transaction. Whoever sends it pays the storage deposit
166// of the bytes it adds and receives the refund of the bytes it frees. In a
167// transaction, the three byte arguments are written in base64, which the
168// chain decodes before the call.
169func Bind(cur realm, account address, leaf int, keyType string, key, proofSHA256, proofKeccak256 []byte) {
170	account = canonical(account)
171	c := mustGet(account)
172	checkKeyType(keyType)
173	if len(key) == 0 || len(key) > MaxKeySize {
174		panic("key must be between 1 and " + strconv.Itoa(MaxKeySize) + " bytes long")
175	}
176
177	msg := qrc.BindMessage(commitID(cur, account, c), uint32(leaf), keyType, key)
178	spend(c, leaf, msg, proofSHA256, proofKeccak256)
179
180	if c.keyBinds == 0 {
181		bound++
182	}
183	c.keyType = keyType
184	// A copy: the caller may be a realm that keeps the slice it passed.
185	c.key = append([]byte(nil), key...)
186	c.keyLeaf = leaf
187	c.keyGeneration = c.generation
188	c.keyAt = runtime.ChainHeight()
189	c.keyBinds++
190
191	chain.Emit("Bound",
192		"account", account.String(),
193		"leaf", strconv.Itoa(leaf),
194		"generation", strconv.FormatUint(uint64(c.generation), 10),
195		"keyType", keyType,
196		"keySize", strconv.Itoa(len(key)),
197		"keySHA256", hashHex(key),
198	)
199}
200
201// Rotate replaces the commit of account by a new one: two new roots, hex
202// encoded, and their height. The public key bound to the account stays.
203// Nothing checks the new roots any more than Register checks the first ones.
204//
205// The request must be signed with one-time key number leaf of both current
206// trees: the proofs are those of qrc.RotateMessage for these arguments, with
207// the account written as the chain writes it (lower case). Proofs against
208// the replaced trees are refused afterwards. The registry cannot see inside
209// new roots: new trees must not reuse the old keys. The Rotated event
210// reports the new generation; its leaf belongs to the one before.
211//
212// A signed rotation stays valid until its leaf is spent or the account
213// rotates: only another rotation can cancel it.
214//
215// Anyone may send the transaction. Whoever sends it pays the storage deposit
216// of the bytes it adds and receives the refund of the bytes it frees. In a
217// transaction, the two proofs are written in base64, which the chain decodes
218// before the call.
219func Rotate(cur realm, account address, leaf int, rootSHA256, rootKeccak256 string, height int, proofSHA256, proofKeccak256 []byte) {
220	account = canonical(account)
221	c := mustGet(account)
222	newSHA256 := decodeRoot(rootSHA256)
223	newKeccak256 := decodeRoot(rootKeccak256)
224	checkTrees(newSHA256, newKeccak256, height)
225	if c.knows(newSHA256) || c.knows(newKeccak256) {
226		panic("a root of this account can never be registered again")
227	}
228
229	msg := qrc.RotateMessage(commitID(cur, account, c), uint32(leaf), newSHA256, newKeccak256, height)
230	spend(c, leaf, msg, proofSHA256, proofKeccak256)
231
232	c.retired = append(c.retired, c.rootSHA256[:]...)
233	c.retired = append(c.retired, c.rootKeccak256[:]...)
234	c.rootSHA256 = newSHA256
235	c.rootKeccak256 = newKeccak256
236	c.height = height
237	c.generation++
238	c.used = make([]byte, qrc.Leaves(height)/8)
239	c.usedCount = 0
240	c.rotatedAt = runtime.ChainHeight()
241
242	chain.Emit("Rotated",
243		"account", account.String(),
244		"leaf", strconv.Itoa(leaf),
245		"generation", strconv.FormatUint(uint64(c.generation), 10),
246		"rootSHA256", hex.EncodeToString(newSHA256[:]),
247		"rootKeccak256", hex.EncodeToString(newKeccak256[:]),
248		"height", strconv.Itoa(height),
249	)
250}
251
252// Authorize spends one-time key number leaf of account on payload, on behalf
253// of the calling realm. It returns only if both proofs are valid signatures
254// of qrc.AuthorizeMessage for the caller's package path and payload, and
255// panics otherwise. account must be written as the chain writes it, in
256// lower-case bech32, so that the calling realm holds exactly the account
257// whose keys signed.
258//
259// It lets a realm act for an account on the sole strength of its recovery
260// keys. A proof made for one realm is useless to any other, and what the
261// payload means is entirely up to the caller. An approval stays valid until
262// its leaf is spent or the account rotates: the registry gives it no
263// deadline and no nonce, so an app must put both in the payload and check
264// them. The approval names a package path, not code: check what runs at
265// that path before signing.
266//
267// The calling realm sees the proofs before its transaction ends and may
268// still make it fail, which leaves the leaf unspent here although its
269// signature is public. A wallet must treat a leaf as spent as soon as a
270// signature made with it leaves the wallet, and never sign anything else
271// with it.
272func Authorize(cur realm, account address, leaf int, payload, proofSHA256, proofKeccak256 []byte) {
273	caller := cur.Previous()
274	if caller.IsUser() {
275		panic("only a realm can call Authorize")
276	}
277	app := caller.PkgPath()
278	if canonical(account) != account {
279		panic("write the account as the chain does, in lower-case bech32")
280	}
281	c := mustGet(account)
282
283	msg := qrc.AuthorizeMessage(commitID(cur, account, c), uint32(leaf), app, payload)
284	spend(c, leaf, msg, proofSHA256, proofKeccak256)
285
286	chain.Emit("Authorized",
287		"account", account.String(),
288		"leaf", strconv.Itoa(leaf),
289		"generation", strconv.FormatUint(uint64(c.generation), 10),
290		"app", app,
291		"payloadSHA256", hashHex(payload),
292	)
293}
294
295// spend checks that msg is signed with one-time key number leaf of both trees
296// of c, then marks the leaf as used. It panics, leaving c as it was, if the
297// leaf was used before or if either proof fails.
298func spend(c *commit, leaf int, msg, proofSHA256, proofKeccak256 []byte) {
299	if leaf < 0 || leaf >= qrc.Leaves(c.height) {
300		panic("leaf out of range")
301	}
302	if c.isUsed(leaf) {
303		panic("this one-time key was already used")
304	}
305	if err := qrc.Verify(qrc.SHA256, c.rootSHA256, c.height, leaf, msg, proofSHA256); err != nil {
306		panic("sha256 proof rejected: " + err.Error())
307	}
308	if err := qrc.Verify(qrc.Keccak256, c.rootKeccak256, c.height, leaf, msg, proofKeccak256); err != nil {
309		panic("keccak256 proof rejected: " + err.Error())
310	}
311	c.used[leaf>>3] |= 1 << uint(leaf&7)
312	c.usedCount++
313}
314
315func (c *commit) isUsed(leaf int) bool {
316	return c.used[leaf>>3]&(1<<uint(leaf&7)) != 0
317}
318
319// knows reports whether root is, or ever was, a root of the account.
320func (c *commit) knows(root [qrc.HashSize]byte) bool {
321	if root == c.rootSHA256 || root == c.rootKeccak256 {
322		return true
323	}
324	for at := 0; at < len(c.retired); at += qrc.HashSize {
325		var old [qrc.HashSize]byte
326		copy(old[:], c.retired[at:at+qrc.HashSize])
327		if root == old {
328			return true
329		}
330	}
331	return false
332}
333
334// commitID returns the ID that messages signed for the current commit of
335// account must carry.
336func commitID(cur realm, account address, c *commit) qrc.ID {
337	return qrc.ID{
338		ChainID:    runtime.ChainID(),
339		Registry:   cur.PkgPath(),
340		Account:    account.String(),
341		Generation: c.generation,
342	}
343}
344
345// canonical returns account as the chain itself writes it: in lower case,
346// with the bech32 checksum.
347//
348// The chain reads the same 20 bytes in four spellings, in lower or upper
349// case (as in QR codes) and with the bech32 or the bech32m checksum, and
350// IsValid accepts all four. Commits are kept, signed for and reported under
351// the lower-case bech32 one, the one the chain gives the caller of Register.
352// Bind, Rotate and the views fold the other three to it; Authorize refuses
353// them. Anything else, mixed case included, is no address and comes back as
354// it is, to be found nowhere.
355func canonical(account address) address {
356	s := account.String()
357	// Commits are kept under the canonical spelling, so a spelling that is
358	// found needs no decoding, which costs some 7 million gas.
359	if commits.Has(s) {
360		return account
361	}
362	hrp, data, err := bech32.DecodeToBase256(s)
363	if err != nil || hrp != "g" || len(data) != 20 {
364		return account
365	}
366	canon, err := bech32.EncodeFromBase256(hrp, data)
367	if err != nil {
368		return account
369	}
370	return address(canon)
371}
372
373// get returns the commit of account, or nil if it has none. The account must
374// be in its canonical form.
375func get(account address) *commit {
376	v := commits.Get(account.String())
377	if v == nil {
378		return nil
379	}
380	return v.(*commit)
381}
382
383func mustGet(account address) *commit {
384	c := get(account)
385	if c == nil {
386		panic("this account has no commit")
387	}
388	return c
389}
390
391func hashHex(b []byte) string {
392	sum := sha256.Sum256(b)
393	return hex.EncodeToString(sum[:])
394}
395
396func checkTrees(rootSHA256, rootKeccak256 [qrc.HashSize]byte, height int) {
397	if height < qrc.MinHeight || height > qrc.MaxHeight {
398		panic("height must be between " + strconv.Itoa(qrc.MinHeight) + " and " + strconv.Itoa(qrc.MaxHeight))
399	}
400	var zero [qrc.HashSize]byte
401	if rootSHA256 == zero || rootKeccak256 == zero {
402		panic("a root cannot be all zeros")
403	}
404	if rootSHA256 == rootKeccak256 {
405		panic("the two roots must come from two different trees")
406	}
407}
408
409func checkKeyType(keyType string) {
410	if len(keyType) == 0 || len(keyType) > MaxKeyTypeSize {
411		panic("key type must be between 1 and " + strconv.Itoa(MaxKeyTypeSize) + " characters long")
412	}
413	for i := 0; i < len(keyType); i++ {
414		ch := keyType[i]
415		switch {
416		case ch >= 'a' && ch <= 'z', ch >= 'A' && ch <= 'Z', ch >= '0' && ch <= '9':
417		case i > 0 && (ch == '-' || ch == '.' || ch == '_' || ch == '+' || ch == '/'):
418		default:
419			panic("key type may only hold letters, digits and - . _ + /, and must start with a letter or a digit")
420		}
421	}
422}
423
424func decodeRoot(s string) [qrc.HashSize]byte {
425	var root [qrc.HashSize]byte
426	b, err := hex.DecodeString(s)
427	if err != nil || len(b) != qrc.HashSize {
428		panic("a root must be 64 hexadecimal characters")
429	}
430	copy(root[:], b)
431	return root
432}