Playground
gnomod.toml
module = "gno.land/r/nym-rootlatch001/qrcregistry/v1" gno = "0.9" [addpkg] creator = "g14cryly8jxp54tjdaldvu6n2vsv5c4w0hwlt4fa" height = 1650652 max_deposit = "26000000ugnot"
registry.gno
// Package qrcregistry keeps the Quantum Recovery Commit of user accounts.
//
// A commit is a pair of Merkle roots, each standing for at least 64 Lamport
// one-time keys, one tree hashed with SHA-256 and the other with Keccak-256
// (see package qrc). An account registers its commit once, with an ordinary
// transaction, while its usual key can still be trusted. From then on the
// one-time keys, and nothing else, can speak for the account in this realm:
//
// - Bind registers new public key bytes of any kind for the account,
// - Rotate replaces the commit before its keys run out,
// - Authorize lets another realm spend a key on a request of its own.
//
// Bind and Rotate are open to any sender, and Authorize to any realm, for
// approvals made out to that realm's package path. What they check is a pair
// of hash-based signatures, one per tree, never who signed the transaction.
// An account whose usual key has been broken can therefore still name a new
// public key here, and whoever broke that key cannot touch the commit. This
// realm only records that key: for it to sign for the account would take a
// change to the chain.
//
// Each one-time key signs once. Once every key of a commit is spent, the
// account can never bind, rotate or authorize again here, and the key bound
// last stays for good, so a wallet keeps the last key of a commit for a
// rotation. A commit is never deleted: what it stores keeps its storage
// deposit.
//
// The realm has no owner, no administrator and no parameter that can change
// after deployment.
package qrcregistry
import (
"chain"
"chain/runtime"
"crypto/bech32"
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nym-rootlatch001/qrc/v1"
)
const (
// MaxKeySize is the largest public key, in bytes, Bind accepts. It is 25
// times the largest signature public key standardized so far
// (ML-DSA-87, 2592 bytes).
MaxKeySize = 1 << 16
// MaxKeyTypeSize is the longest key type label, in bytes, Bind accepts.
MaxKeyTypeSize = 64
)
// commit is everything the registry knows about one account.
type commit struct {
rootSHA256 [qrc.HashSize]byte
rootKeccak256 [qrc.HashSize]byte
height int
generation uint32 // number of rotations so far
used []byte // one bit per leaf of the current trees, set once spent
usedCount int
retired []byte // both roots of every earlier generation, 64 bytes each
rank int // 1 for the first account that registered
registeredAt int64 // block height of the registration
registeredTime int64 // block time of the registration, Unix seconds
rotatedAt int64 // block height of the last rotation, 0 if none
keyType string // label of the public key last bound, "" if none
key []byte
keyLeaf int // leaf that signed for the key
keyGeneration uint32 // generation of the trees keyLeaf belongs to
keyAt int64 // block height at which the key was bound
keyBinds int // number of keys bound so far
}
// latestKept is the number of accounts the home page lists.
const latestKept = 10
var (
commits avl.Tree // address -> *commit
bound int // number of accounts with a bound key
// latest holds the accounts that registered last, newest first, at most
// latestKept of them. It is all the home page needs, and unlike an index
// of every registration it costs a new account nothing to keep. The full
// history is in the Registered events.
latest []string
)
// Register stores the Quantum Recovery Commit of the calling account: the
// roots of its SHA-256 and Keccak-256 trees, hex encoded, and their height.
//
// An account registers once. Its usual key has no say over the commit
// afterwards; only the one-time keys can replace it, through Rotate.
//
// A registration can never be corrected or withdrawn, and nothing here
// checks that the roots are a SHA-256 tree and a Keccak-256 tree of the
// given height: derive both roots and the height from the kit, in this
// order, and check them before sending. The caller must be the account
// itself, in a direct call or in a script it runs; a session key is refused.
func Register(cur realm, rootSHA256, rootKeccak256 string, height int) {
// cur belongs to this very call: the runtime makes it on the way in, so
// it needs no IsCurrent check, and its Previous is whoever called.
caller := cur.Previous()
if !caller.IsUser() {
panic("only a user account can register a commit")
}
if _, _, _, isSession := runtime.GetSessionInfo(); isSession {
panic("a commit must be registered with the account's own key, not a session key")
}
account := caller.Address().String()
if commits.Has(account) {
panic("this account already has a commit: only its one-time keys can replace it")
}
c := &commit{
rootSHA256: decodeRoot(rootSHA256),
rootKeccak256: decodeRoot(rootKeccak256),
height: height,
rank: commits.Size() + 1,
registeredAt: runtime.ChainHeight(),
registeredTime: time.Now().Unix(),
}
checkTrees(c.rootSHA256, c.rootKeccak256, height)
c.used = make([]byte, qrc.Leaves(height)/8)
commits.Set(account, c)
if len(latest) < latestKept {
latest = append(latest, "")
}
for i := len(latest) - 1; i > 0; i-- {
latest[i] = latest[i-1]
}
latest[0] = account
chain.Emit("Registered",
"account", account,
"rootSHA256", hex.EncodeToString(c.rootSHA256[:]),
"rootKeccak256", hex.EncodeToString(c.rootKeccak256[:]),
"height", strconv.Itoa(height),
"rank", strconv.Itoa(c.rank),
)
}
// Bind registers key as the new public key of account, under the free label
// keyType (for instance "ML-DSA-65"). key holds 1 to MaxKeySize bytes; a
// scheme with a longer public key can bind a digest of it, under a label
// that says so.
//
// The request must be signed with one-time key number leaf of both trees of
// the account: proofSHA256 and proofKeccak256 are the proofs of
// qrc.BindMessage for these arguments, with the account written as the chain
// writes it (lower case), whatever spelling the account argument uses. The
// leaf is spent.
//
// A signed request stays valid until its leaf is spent or the account
// rotates, and whoever holds it may send it at any time: requests take
// effect in the order they land, not the order they were signed. To replace
// a key while an earlier Bind for another key may still be pending, rotate
// first, bind in the new generation, then check Key. After a failure, send
// the same signed request again rather than sign for another key.
//
// Anyone may send the transaction. Whoever sends it pays the storage deposit
// of the bytes it adds and receives the refund of the bytes it frees. In a
// transaction, the three byte arguments are written in base64, which the
// chain decodes before the call.
func Bind(cur realm, account address, leaf int, keyType string, key, proofSHA256, proofKeccak256 []byte) {
account = canonical(account)
c := mustGet(account)
checkKeyType(keyType)
if len(key) == 0 || len(key) > MaxKeySize {
panic("key must be between 1 and " + strconv.Itoa(MaxKeySize) + " bytes long")
}
msg := qrc.BindMessage(commitID(cur, account, c), uint32(leaf), keyType, key)
spend(c, leaf, msg, proofSHA256, proofKeccak256)
if c.keyBinds == 0 {
bound++
}
c.keyType = keyType
// A copy: the caller may be a realm that keeps the slice it passed.
c.key = append([]byte(nil), key...)
c.keyLeaf = leaf
c.keyGeneration = c.generation
c.keyAt = runtime.ChainHeight()
c.keyBinds++
chain.Emit("Bound",
"account", account.String(),
"leaf", strconv.Itoa(leaf),
"generation", strconv.FormatUint(uint64(c.generation), 10),
"keyType", keyType,
"keySize", strconv.Itoa(len(key)),
"keySHA256", hashHex(key),
)
}
// Rotate replaces the commit of account by a new one: two new roots, hex
// encoded, and their height. The public key bound to the account stays.
// Nothing checks the new roots any more than Register checks the first ones.
//
// The request must be signed with one-time key number leaf of both current
// trees: the proofs are those of qrc.RotateMessage for these arguments, with
// the account written as the chain writes it (lower case). Proofs against
// the replaced trees are refused afterwards. The registry cannot see inside
// new roots: new trees must not reuse the old keys. The Rotated event
// reports the new generation; its leaf belongs to the one before.
//
// A signed rotation stays valid until its leaf is spent or the account
// rotates: only another rotation can cancel it.
//
// Anyone may send the transaction. Whoever sends it pays the storage deposit
// of the bytes it adds and receives the refund of the bytes it frees. In a
// transaction, the two proofs are written in base64, which the chain decodes
// before the call.
func Rotate(cur realm, account address, leaf int, rootSHA256, rootKeccak256 string, height int, proofSHA256, proofKeccak256 []byte) {
account = canonical(account)
c := mustGet(account)
newSHA256 := decodeRoot(rootSHA256)
newKeccak256 := decodeRoot(rootKeccak256)
checkTrees(newSHA256, newKeccak256, height)
if c.knows(newSHA256) || c.knows(newKeccak256) {
panic("a root of this account can never be registered again")
}
msg := qrc.RotateMessage(commitID(cur, account, c), uint32(leaf), newSHA256, newKeccak256, height)
spend(c, leaf, msg, proofSHA256, proofKeccak256)
c.retired = append(c.retired, c.rootSHA256[:]...)
c.retired = append(c.retired, c.rootKeccak256[:]...)
c.rootSHA256 = newSHA256
c.rootKeccak256 = newKeccak256
c.height = height
c.generation++
c.used = make([]byte, qrc.Leaves(height)/8)
c.usedCount = 0
c.rotatedAt = runtime.ChainHeight()
chain.Emit("Rotated",
"account", account.String(),
"leaf", strconv.Itoa(leaf),
"generation", strconv.FormatUint(uint64(c.generation), 10),
"rootSHA256", hex.EncodeToString(newSHA256[:]),
"rootKeccak256", hex.EncodeToString(newKeccak256[:]),
"height", strconv.Itoa(height),
)
}
// Authorize spends one-time key number leaf of account on payload, on behalf
// of the calling realm. It returns only if both proofs are valid signatures
// of qrc.AuthorizeMessage for the caller's package path and payload, and
// panics otherwise. account must be written as the chain writes it, in
// lower-case bech32, so that the calling realm holds exactly the account
// whose keys signed.
//
// It lets a realm act for an account on the sole strength of its recovery
// keys. A proof made for one realm is useless to any other, and what the
// payload means is entirely up to the caller. An approval stays valid until
// its leaf is spent or the account rotates: the registry gives it no
// deadline and no nonce, so an app must put both in the payload and check
// them. The approval names a package path, not code: check what runs at
// that path before signing.
//
// The calling realm sees the proofs before its transaction ends and may
// still make it fail, which leaves the leaf unspent here although its
// signature is public. A wallet must treat a leaf as spent as soon as a
// signature made with it leaves the wallet, and never sign anything else
// with it.
func Authorize(cur realm, account address, leaf int, payload, proofSHA256, proofKeccak256 []byte) {
caller := cur.Previous()
if caller.IsUser() {
panic("only a realm can call Authorize")
}
app := caller.PkgPath()
if canonical(account) != account {
panic("write the account as the chain does, in lower-case bech32")
}
c := mustGet(account)
msg := qrc.AuthorizeMessage(commitID(cur, account, c), uint32(leaf), app, payload)
spend(c, leaf, msg, proofSHA256, proofKeccak256)
chain.Emit("Authorized",
"account", account.String(),
"leaf", strconv.Itoa(leaf),
"generation", strconv.FormatUint(uint64(c.generation), 10),
"app", app,
"payloadSHA256", hashHex(payload),
)
}
// spend checks that msg is signed with one-time key number leaf of both trees
// of c, then marks the leaf as used. It panics, leaving c as it was, if the
// leaf was used before or if either proof fails.
func spend(c *commit, leaf int, msg, proofSHA256, proofKeccak256 []byte) {
if leaf < 0 || leaf >= qrc.Leaves(c.height) {
panic("leaf out of range")
}
if c.isUsed(leaf) {
panic("this one-time key was already used")
}
if err := qrc.Verify(qrc.SHA256, c.rootSHA256, c.height, leaf, msg, proofSHA256); err != nil {
panic("sha256 proof rejected: " + err.Error())
}
if err := qrc.Verify(qrc.Keccak256, c.rootKeccak256, c.height, leaf, msg, proofKeccak256); err != nil {
panic("keccak256 proof rejected: " + err.Error())
}
c.used[leaf>>3] |= 1 << uint(leaf&7)
c.usedCount++
}
func (c *commit) isUsed(leaf int) bool {
return c.used[leaf>>3]&(1<<uint(leaf&7)) != 0
}
// knows reports whether root is, or ever was, a root of the account.
func (c *commit) knows(root [qrc.HashSize]byte) bool {
if root == c.rootSHA256 || root == c.rootKeccak256 {
return true
}
for at := 0; at < len(c.retired); at += qrc.HashSize {
var old [qrc.HashSize]byte
copy(old[:], c.retired[at:at+qrc.HashSize])
if root == old {
return true
}
}
return false
}
// commitID returns the ID that messages signed for the current commit of
// account must carry.
func commitID(cur realm, account address, c *commit) qrc.ID {
return qrc.ID{
ChainID: runtime.ChainID(),
Registry: cur.PkgPath(),
Account: account.String(),
Generation: c.generation,
}
}
// canonical returns account as the chain itself writes it: in lower case,
// with the bech32 checksum.
//
// The chain reads the same 20 bytes in four spellings, in lower or upper
// case (as in QR codes) and with the bech32 or the bech32m checksum, and
// IsValid accepts all four. Commits are kept, signed for and reported under
// the lower-case bech32 one, the one the chain gives the caller of Register.
// Bind, Rotate and the views fold the other three to it; Authorize refuses
// them. Anything else, mixed case included, is no address and comes back as
// it is, to be found nowhere.
func canonical(account address) address {
s := account.String()
// Commits are kept under the canonical spelling, so a spelling that is
// found needs no decoding, which costs some 7 million gas.
if commits.Has(s) {
return account
}
hrp, data, err := bech32.DecodeToBase256(s)
if err != nil || hrp != "g" || len(data) != 20 {
return account
}
canon, err := bech32.EncodeFromBase256(hrp, data)
if err != nil {
return account
}
return address(canon)
}
// get returns the commit of account, or nil if it has none. The account must
// be in its canonical form.
func get(account address) *commit {
v := commits.Get(account.String())
if v == nil {
return nil
}
return v.(*commit)
}
func mustGet(account address) *commit {
c := get(account)
if c == nil {
panic("this account has no commit")
}
return c
}
func hashHex(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
func checkTrees(rootSHA256, rootKeccak256 [qrc.HashSize]byte, height int) {
if height < qrc.MinHeight || height > qrc.MaxHeight {
panic("height must be between " + strconv.Itoa(qrc.MinHeight) + " and " + strconv.Itoa(qrc.MaxHeight))
}
var zero [qrc.HashSize]byte
if rootSHA256 == zero || rootKeccak256 == zero {
panic("a root cannot be all zeros")
}
if rootSHA256 == rootKeccak256 {
panic("the two roots must come from two different trees")
}
}
func checkKeyType(keyType string) {
if len(keyType) == 0 || len(keyType) > MaxKeyTypeSize {
panic("key type must be between 1 and " + strconv.Itoa(MaxKeyTypeSize) + " characters long")
}
for i := 0; i < len(keyType); i++ {
ch := keyType[i]
switch {
case ch >= 'a' && ch <= 'z', ch >= 'A' && ch <= 'Z', ch >= '0' && ch <= '9':
case i > 0 && (ch == '-' || ch == '.' || ch == '_' || ch == '+' || ch == '/'):
default:
panic("key type may only hold letters, digits and - . _ + /, and must start with a letter or a digit")
}
}
}
func decodeRoot(s string) [qrc.HashSize]byte {
var root [qrc.HashSize]byte
b, err := hex.DecodeString(s)
if err != nil || len(b) != qrc.HashSize {
panic("a root must be 64 hexadecimal characters")
}
copy(root[:], b)
return root
}
registry_test.gno
package qrcregistry
import (
"chain/runtime"
"crypto/bech32"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strconv"
"strings"
"testing"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nym-rootlatch001/qrc/v1"
"gno.land/p/nym-rootlatch001/qrcsigner/v1"
)
const registryPath = "gno.land/r/nym-rootlatch001/qrcregistry/v1"
// holder plays the owner of an account: it holds the one-time keys of one
// commit and signs requests with them, as a wallet would off-chain.
type holder struct {
account address
id qrc.ID
height int
kit *qrcsigner.Kit
}
// newHolder derives the commit number generation of account. The entropy
// depends on the account alone, so that every generation of an account comes
// from one secret, as it does in a wallet.
func newHolder(account address, generation uint32) *holder {
return newHolderAt(account, generation, qrc.MinHeight)
}
// newHolderAt is newHolder for trees of the given height.
func newHolderAt(account address, generation uint32, height int) *holder {
entropy := sha256.Sum256([]byte("test entropy of " + account.String()))
id := qrc.ID{
ChainID: runtime.ChainID(),
Registry: registryPath,
Account: account.String(),
Generation: generation,
}
return &holder{account: account, id: id, height: height, kit: qrcsigner.New(entropy[:], id, height)}
}
func (h *holder) roots() (rootSHA256, rootKeccak256 string) {
a, b := h.kit.Roots()
return hex.EncodeToString(a[:]), hex.EncodeToString(b[:])
}
func (h *holder) signBind(leaf int, keyType string, key []byte) (proofSHA256, proofKeccak256 []byte) {
return h.kit.Sign(leaf, qrc.BindMessage(h.id, uint32(leaf), keyType, key))
}
func (h *holder) signRotate(leaf int, next *holder) (proofSHA256, proofKeccak256 []byte) {
rootSHA256, rootKeccak256 := next.kit.Roots()
return h.kit.Sign(leaf, qrc.RotateMessage(h.id, uint32(leaf), rootSHA256, rootKeccak256, next.height))
}
func (h *holder) signAuthorize(leaf int, app string, payload []byte) (proofSHA256, proofKeccak256 []byte) {
return h.kit.Sign(leaf, qrc.AuthorizeMessage(h.id, uint32(leaf), app, payload))
}
// register registers h's commit. The test must have made h's account the
// caller beforehand: testing.SetRealm only acts on the function that calls
// it, so it cannot be called from here. The realm comes second because a
// function that takes it first is a crossing function.
func register(h *holder, rlm realm) {
rootSHA256, rootKeccak256 := h.roots()
Register(cross(rlm), rootSHA256, rootKeccak256, qrc.MinHeight)
}
// tamper returns a copy of proof with one bit of its byte number at flipped.
func tamper(proof []byte, at int) []byte {
changed := append([]byte(nil), proof...)
changed[at] ^= 0x01
return changed
}
var (
// relayer has nothing to do with any commit. Requests sent from it must
// stand on the one-time keys alone.
relayer = testing.NewUserRealm(testutils.TestAddress("relayer"))
testKey = []byte("these bytes stand for a public key of a scheme chosen after D-day")
)
func TestRegister(cur realm, t *testing.T) {
alice := testutils.TestAddress("reg-alice")
h := newHolder(alice, 0)
rootSHA256, rootKeccak256 := h.roots()
zero := strings.Repeat("00", qrc.HashSize)
accounts, withKey := Count()
uassert.False(t, Has(alice))
uassert.Equal(t, "null", Lookup(alice))
// A realm cannot hold a commit, nor register one for the user calling it.
testing.SetRealm(testing.NewCodeRealm("gno.land/r/someone/app"))
uassert.AbortsContains(t, cur, "only a user account", func() {
Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "64 hexadecimal characters", func() {
Register(cross(cur), rootSHA256[:62], rootKeccak256, qrc.MinHeight)
})
uassert.AbortsContains(t, cur, "64 hexadecimal characters", func() {
Register(cross(cur), rootSHA256, "zz"+rootKeccak256[2:], qrc.MinHeight)
})
uassert.AbortsContains(t, cur, "cannot be all zeros", func() {
Register(cross(cur), zero, rootKeccak256, qrc.MinHeight)
})
uassert.AbortsContains(t, cur, "cannot be all zeros", func() {
Register(cross(cur), rootSHA256, zero, qrc.MinHeight)
})
uassert.AbortsContains(t, cur, "two different trees", func() {
Register(cross(cur), rootSHA256, rootSHA256, qrc.MinHeight)
})
uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight-1)
})
uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
Register(cross(cur), rootSHA256, rootKeccak256, qrc.MaxHeight+1)
})
uassert.False(t, Has(alice), "a rejected registration must leave nothing behind")
Register(cross(cur), rootSHA256, rootKeccak256, qrc.MinHeight)
uassert.True(t, Has(alice))
nowAccounts, nowWithKey := Count()
uassert.Equal(t, accounts+1, nowAccounts)
uassert.Equal(t, withKey, nowWithKey)
for leaf := 0; leaf < qrc.Leaves(qrc.MinHeight); leaf++ {
if IsUsed(alice, leaf) {
t.Fatalf("leaf %d is used right after registration", leaf)
}
}
if _, _, ok := Key(alice); ok {
t.Fatalf("a key is bound right after registration")
}
uassert.Equal(t, "", KeyBase64(alice))
// The usual key of the account has no say over the commit any more.
other := newHolder(alice, 1)
otherSHA256, otherKeccak256 := other.roots()
uassert.AbortsContains(t, cur, "already has a commit", func() {
Register(cross(cur), otherSHA256, otherKeccak256, qrc.MinHeight)
})
uassert.True(t, strings.Contains(Lookup(alice), `"rootSHA256":"`+rootSHA256+`"`))
}
func TestBind(cur realm, t *testing.T) {
alice := testutils.TestAddress("bind-alice")
mallory := testutils.TestAddress("bind-mallory")
h := newHolder(alice, 0)
testing.SetRealm(testing.NewUserRealm(alice))
register(h, cur)
_, withKey := Count()
proofSHA256, proofKeccak256 := h.signBind(3, "ML-DSA-65", testKey)
// Nothing here depends on who sends the transaction.
testing.SetRealm(relayer)
uassert.AbortsContains(t, cur, "no commit", func() {
Bind(cross(cur), mallory, 3, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "leaf out of range", func() {
Bind(cross(cur), alice, 64, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "leaf out of range", func() {
Bind(cross(cur), alice, -1, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key type", func() {
Bind(cross(cur), alice, 3, "", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key type", func() {
Bind(cross(cur), alice, 3, "ML DSA <65>", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key type", func() {
Bind(cross(cur), alice, 3, "-ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key type", func() {
Bind(cross(cur), alice, 3, strings.Repeat("k", MaxKeyTypeSize+1), testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key must be between", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", nil, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "key must be between", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", make([]byte, MaxKeySize+1), proofSHA256, proofKeccak256)
})
// A signature covers the leaf, the label and every byte of the key.
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 4, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-87", testKey, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", append([]byte("x"), testKey...), proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", tamper(testKey, len(testKey)-1), proofSHA256, proofKeccak256)
})
// Both trees must agree: one valid proof is not enough.
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, tamper(proofSHA256, 0), proofKeccak256)
})
uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, tamper(proofKeccak256, 0))
})
uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, tamper(proofKeccak256, qrc.SignatureSize+5))
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofKeccak256, proofSHA256)
})
uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, proofSHA256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected: qrc: proof has the wrong size", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256[:len(proofSHA256)-1], proofKeccak256)
})
uassert.AbortsContains(t, cur, "keccak256 proof rejected: qrc: proof has the wrong size", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, nil)
})
// Keys of another account's commit are useless here.
stranger := newHolder(mallory, 0)
strangerSHA256, strangerKeccak256 := stranger.signBind(3, "ML-DSA-65", testKey)
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, strangerSHA256, strangerKeccak256)
})
// None of the rejected requests cost the account a one-time key.
for leaf := 0; leaf < qrc.Leaves(qrc.MinHeight); leaf++ {
if IsUsed(alice, leaf) {
t.Fatalf("leaf %d was burned by a rejected request", leaf)
}
}
if _, _, ok := Key(alice); ok {
t.Fatalf("a rejected request bound a key")
}
sent := append([]byte(nil), testKey...)
Bind(cross(cur), alice, 3, "ML-DSA-65", sent, proofSHA256, proofKeccak256)
keyType, got, ok := Key(alice)
uassert.True(t, ok)
uassert.Equal(t, "ML-DSA-65", keyType)
uassert.Equal(t, string(testKey), string(got))
uassert.Equal(t, base64.StdEncoding.EncodeToString(testKey), KeyBase64(alice))
uassert.True(t, IsUsed(alice, 3))
uassert.False(t, IsUsed(alice, 2))
uassert.False(t, IsUsed(alice, 4))
_, nowWithKey := Count()
uassert.Equal(t, withKey+1, nowWithKey)
// The stored key shares no memory with what came in or with what goes out.
sent[0] ^= 0xff
got[1] ^= 0xff
_, again, _ := Key(alice)
uassert.Equal(t, string(testKey), string(again))
// A one-time key signs once.
uassert.AbortsContains(t, cur, "already used", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
})
// Binding again, with a fresh leaf, replaces the key.
second := []byte("a second public key")
secondSHA256, secondKeccak256 := h.signBind(63, "SLH-DSA-SHA2-128s", second)
Bind(cross(cur), alice, 63, "SLH-DSA-SHA2-128s", second, secondSHA256, secondKeccak256)
keyType, got, _ = Key(alice)
uassert.Equal(t, "SLH-DSA-SHA2-128s", keyType)
uassert.Equal(t, string(second), string(got))
uassert.True(t, IsUsed(alice, 63))
_, nowWithKey = Count()
uassert.Equal(t, withKey+1, nowWithKey, "an account counts once however many keys it bound")
}
func TestRotate(cur realm, t *testing.T) {
alice := testutils.TestAddress("rot-alice")
first := newHolder(alice, 0)
second := newHolder(alice, 1)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
firstSHA256, firstKeccak256 := first.roots()
secondSHA256, secondKeccak256 := second.roots()
testing.SetRealm(relayer)
keySHA256, keyKeccak256 := first.signBind(0, "ML-DSA-65", testKey)
Bind(cross(cur), alice, 0, "ML-DSA-65", testKey, keySHA256, keyKeccak256)
proofSHA256, proofKeccak256 := first.signRotate(1, second)
// The signature covers both new roots and the height.
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Rotate(cross(cur), alice, 1, secondKeccak256, secondSHA256, qrc.MinHeight, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight+1, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Rotate(cross(cur), alice, 2, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "keccak256 proof rejected", func() {
Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, tamper(proofKeccak256, 77))
})
uassert.AbortsContains(t, cur, "height must be between 6 and 16", func() {
Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, 5, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "two different trees", func() {
Rotate(cross(cur), alice, 1, secondSHA256, secondSHA256, qrc.MinHeight, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "no commit", func() {
Rotate(cross(cur), testutils.TestAddress("rot-nobody"), 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
})
// A request to keep a current root is refused even when properly signed.
sameSHA256, sameKeccak256 := first.signRotate(1, first)
uassert.AbortsContains(t, cur, "never be registered again", func() {
Rotate(cross(cur), alice, 1, firstSHA256, firstKeccak256, qrc.MinHeight, sameSHA256, sameKeccak256)
})
uassert.False(t, IsUsed(alice, 1))
Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
lookup := Lookup(alice)
uassert.True(t, strings.Contains(lookup, `"generation":1`), lookup)
uassert.True(t, strings.Contains(lookup, `"rootSHA256":"`+secondSHA256+`"`), lookup)
uassert.True(t, strings.Contains(lookup, `"rootKeccak256":"`+secondKeccak256+`"`), lookup)
uassert.True(t, strings.Contains(lookup, `"usedCount":0`), lookup)
uassert.False(t, IsUsed(alice, 0), "the new trees start with every key unused")
uassert.False(t, IsUsed(alice, 1))
// The public key bound before the rotation stays.
keyType, got, ok := Key(alice)
uassert.True(t, ok)
uassert.Equal(t, "ML-DSA-65", keyType)
uassert.Equal(t, string(testKey), string(got))
// Every key of the replaced trees is void, used or not.
other := []byte("another public key")
oldSHA256, oldKeccak256 := first.signBind(2, "ML-DSA-65", other)
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 2, "ML-DSA-65", other, oldSHA256, oldKeccak256)
})
// Sending the rotation request a second time changes nothing.
uassert.AbortsContains(t, cur, "never be registered again", func() {
Rotate(cross(cur), alice, 1, secondSHA256, secondKeccak256, qrc.MinHeight, proofSHA256, proofKeccak256)
})
// The new trees speak for the account from now on.
newSHA256, newKeccak256 := second.signBind(2, "ML-DSA-65", other)
Bind(cross(cur), alice, 2, "ML-DSA-65", other, newSHA256, newKeccak256)
_, got, _ = Key(alice)
uassert.Equal(t, string(other), string(got))
// A retired root never comes back, whichever of the two places it takes.
third := newHolder(alice, 2)
thirdSHA256, thirdKeccak256 := third.roots()
backSHA256, backKeccak256 := second.signRotate(3, first)
uassert.AbortsContains(t, cur, "never be registered again", func() {
Rotate(cross(cur), alice, 3, firstSHA256, firstKeccak256, qrc.MinHeight, backSHA256, backKeccak256)
})
uassert.AbortsContains(t, cur, "never be registered again", func() {
Rotate(cross(cur), alice, 3, thirdSHA256, firstSHA256, qrc.MinHeight, backSHA256, backKeccak256)
})
uassert.AbortsContains(t, cur, "never be registered again", func() {
Rotate(cross(cur), alice, 3, firstKeccak256, thirdKeccak256, qrc.MinHeight, backSHA256, backKeccak256)
})
uassert.False(t, IsUsed(alice, 3))
onSHA256, onKeccak256 := second.signRotate(3, third)
Rotate(cross(cur), alice, 3, thirdSHA256, thirdKeccak256, qrc.MinHeight, onSHA256, onKeccak256)
uassert.True(t, strings.Contains(Lookup(alice), `"generation":2`))
}
func TestAuthorize(cur realm, t *testing.T) {
const (
vault = "gno.land/r/someone/vault"
thief = "gno.land/r/someone/thief"
)
alice := testutils.TestAddress("auth-alice")
h := newHolder(alice, 0)
testing.SetRealm(testing.NewUserRealm(alice))
register(h, cur)
payload := []byte("withdraw 100ugnot to g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5")
proofSHA256, proofKeccak256 := h.signAuthorize(7, vault, payload)
// A user cannot spend a key through Authorize, whatever it is signed for.
testing.SetRealm(relayer)
uassert.AbortsContains(t, cur, "only a realm", func() {
Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
})
testing.SetRealm(testing.NewUserRealm(alice))
uassert.AbortsContains(t, cur, "only a realm", func() {
Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
})
// An approval given to one realm is useless to another.
testing.SetRealm(testing.NewCodeRealm(thief))
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
})
testing.SetRealm(testing.NewCodeRealm(vault))
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Authorize(cross(cur), alice, 7, []byte("withdraw 999ugnot"), proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Authorize(cross(cur), alice, 8, payload, proofSHA256, proofKeccak256)
})
uassert.AbortsContains(t, cur, "no commit", func() {
Authorize(cross(cur), testutils.TestAddress("auth-nobody"), 7, payload, proofSHA256, proofKeccak256)
})
uassert.False(t, IsUsed(alice, 7))
Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
uassert.True(t, IsUsed(alice, 7))
uassert.AbortsContains(t, cur, "already used", func() {
Authorize(cross(cur), alice, 7, payload, proofSHA256, proofKeccak256)
})
// A proof made for Authorize cannot bind a key, and the reverse.
testing.SetRealm(relayer)
authSHA256, authKeccak256 := h.signAuthorize(9, vault, testKey)
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 9, vault, testKey, authSHA256, authKeccak256)
})
bindSHA256, bindKeccak256 := h.signBind(9, vault, testKey)
testing.SetRealm(testing.NewCodeRealm(vault))
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Authorize(cross(cur), alice, 9, testKey, bindSHA256, bindKeccak256)
})
uassert.False(t, IsUsed(alice, 9))
}
// TestLatest registers more accounts than the home page lists and checks
// that it shows the last ones, newest first. A registration only needs two
// roots, so no key is derived here.
func TestLatest(cur realm, t *testing.T) {
const count = latestKept + 2
accounts := make([]address, count)
before, _ := Count()
for i := range accounts {
accounts[i] = testutils.TestAddress("latest-" + string(rune('a'+i)))
rootSHA256 := sha256.Sum256([]byte("sha256 root of " + accounts[i].String()))
rootKeccak256 := sha256.Sum256([]byte("keccak256 root of " + accounts[i].String()))
testing.SetRealm(testing.NewUserRealm(accounts[i]))
Register(cross(cur), hex.EncodeToString(rootSHA256[:]), hex.EncodeToString(rootKeccak256[:]), qrc.MinHeight+i%3)
}
after, _ := Count()
uassert.Equal(t, before+count, after)
uassert.Equal(t, latestKept, len(latest))
home := Render("")
at := 0
for i := count - 1; i >= count-latestKept; i-- {
next := strings.Index(home[at:], accounts[i].String())
if next < 0 {
t.Fatalf("account %d is missing or out of order on the home page:\n%s", i, home)
}
at += next
}
for i := 0; i < count-latestKept; i++ {
uassert.False(t, strings.Contains(home, accounts[i].String()), "an account that left the list is still shown")
uassert.True(t, Has(accounts[i]), "an account that left the list lost its commit")
}
uassert.True(t, strings.Contains(home, "| "+strconv.Itoa(after)+" | "+accounts[count-1].String()+" | 0 of "), home)
// Latest lists the same accounts as the home page, in the same order, one
// JSON object each.
list := Latest()
uassert.True(t, strings.HasPrefix(list, "[{"), list)
uassert.True(t, strings.HasSuffix(list, "}]"), list)
uassert.Equal(t, latestKept, strings.Count(list, `{"account":`), list)
at = 0
for i := count - 1; i >= count-latestKept; i-- {
object := `{"account":"` + accounts[i].String() + `","rank":` + strconv.Itoa(before+i+1) +
`,"height":` + strconv.Itoa(qrc.MinHeight+i%3) + `,"usedCount":0,"generation":0}`
next := strings.Index(list[at:], object)
if next < 0 {
t.Fatalf("account %d is missing, wrong or out of order in Latest:\n%s", i, list)
}
at += next + len(object)
}
for i := 0; i < count-latestKept; i++ {
uassert.False(t, strings.Contains(list, accounts[i].String()), "an account that left the list is still in Latest")
}
}
func TestViews(cur realm, t *testing.T) {
alice := testutils.TestAddress("view-alice")
nobody := testutils.TestAddress("view-nobody")
h := newHolder(alice, 0)
rootSHA256, rootKeccak256 := h.roots()
uassert.True(t, strings.Contains(Render(nobody.String()), "**No commit.**"))
uassert.True(t, strings.Contains(Render("account?address="+nobody.String()), "**No commit.**"))
testing.SetRealm(testing.NewUserRealm(alice))
register(h, cur)
testing.SetRealm(relayer)
home := Render("")
uassert.True(t, strings.Contains(home, "# Quantum Recovery Commits"), home)
uassert.True(t, strings.Contains(home, alice.String()), home)
uassert.True(t, strings.Contains(home, " | "+alice.String()+" | 0 of 64 | none yet |"), home)
page := Render(alice.String())
uassert.True(t, strings.Contains(page, "**Recoverable.**"), page)
uassert.True(t, strings.Contains(page, rootSHA256), page)
uassert.True(t, strings.Contains(page, rootKeccak256), page)
uassert.True(t, strings.Contains(page, "| One-time keys | 64, 0 used |"), page)
uassert.True(t, strings.Contains(page, "| New public key | none yet |"), page)
uassert.Equal(t, page, Render("account?address="+alice.String()))
proofSHA256, proofKeccak256 := h.signBind(10, "ML-DSA-65", testKey)
Bind(cross(cur), alice, 10, "ML-DSA-65", testKey, proofSHA256, proofKeccak256)
digest := sha256.Sum256(testKey)
page = Render(alice.String())
uassert.True(t, strings.Contains(page, "| One-time keys | 64, 1 used |"), page)
uassert.True(t, strings.Contains(page, "`ML-DSA-65`, 65 bytes, SHA-256 `"+hex.EncodeToString(digest[:])+"`"), page)
uassert.True(t, strings.Contains(page, "with one-time key 10"), page)
// Leaf 10 is bit 2 of the second byte of the bitmap.
lookup := Lookup(alice)
uassert.True(t, strings.HasPrefix(lookup, `{"account":"`+alice.String()+`","rank":`), lookup)
uassert.True(t, strings.Contains(lookup, `"generation":0,"rotatedAt":0,"height":6,`), lookup)
uassert.True(t, strings.Contains(lookup, `"used":"0004000000000000","usedCount":1,`), lookup)
uassert.True(t, strings.Contains(lookup, `"keyType":"ML-DSA-65","keySize":65,"keySHA256":"`+hex.EncodeToString(digest[:])+`","keyLeaf":10,`), lookup)
uassert.True(t, strings.HasSuffix(lookup, `,"keyBinds":1}`), lookup)
// Latest gives the label of the bound key, and nothing about the key.
list := Latest()
uassert.True(t, strings.Contains(list, `"account":"`+alice.String()+`","rank":`), list)
uassert.True(t, strings.Contains(list, `,"height":6,"usedCount":1,"generation":0,"keyType":"ML-DSA-65"}`), list)
uassert.False(t, strings.Contains(list, hex.EncodeToString(digest[:])), list)
// Whatever the path holds, the page never repeats it unless it is an address.
for _, path := range []string{
"<script>alert(1)</script>",
"account?address=<script>alert(1)</script>",
"account",
"account?",
"g1notanaddress",
"[click](https://example.com)",
alice.String() + "/extra",
} {
page := Render(path)
uassert.True(t, strings.HasPrefix(page, "# Not an address"), path)
uassert.False(t, strings.Contains(page, "script"), path)
uassert.False(t, strings.Contains(page, "example.com"), path)
}
}
// bech32mOf returns account with the bech32m checksum in place of the bech32
// one: the same 20 bytes, which the chain reads as the same account.
func bech32mOf(account address) address {
hrp, data, err := bech32.Decode(account.String())
if err != nil {
panic(err)
}
spelled, err := bech32.EncodeM(hrp, data)
if err != nil {
panic(err)
}
return address(spelled)
}
// TestSpellings writes an address in capitals, as a QR code does, and with
// the bech32m checksum. The chain reads all four spellings as one account, so
// Bind, Rotate and the views must as well, while Authorize takes only the
// spelling the chain writes, so that the calling realm holds the account that
// signed. What is signed always names the account in lower case.
func TestSpellings(cur realm, t *testing.T) {
const vault = "gno.land/r/someone/vault"
alice := testutils.TestAddress("caps-alice")
loud := address(strings.ToUpper(alice.String()))
quiet := bech32mOf(alice)
loudQuiet := address(strings.ToUpper(quiet.String()))
others := []address{loud, quiet, loudQuiet}
spellings := []address{alice, loud, quiet, loudQuiet}
mixed := address(strings.ToUpper(alice.String()[:20]) + alice.String()[20:])
for _, s := range spellings {
uassert.True(t, s.IsValid(), "the chain takes "+s.String())
uassert.Equal(t, alice.String(), canonical(s).String(), s.String())
}
uassert.False(t, mixed.IsValid(), "the chain refuses an address in mixed case")
uassert.Equal(t, mixed.String(), canonical(mixed).String())
uassert.Equal(t, "", canonical(address("")).String())
uassert.Equal(t, "1234", canonical(address("1234")).String())
uassert.Equal(t, "<script>", canonical(address("<script>")).String())
first := newHolder(alice, 0)
second := newHolder(alice, 1)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
testing.SetRealm(relayer)
for _, s := range spellings {
uassert.True(t, Has(s), s.String())
uassert.Equal(t, Lookup(alice), Lookup(s), s.String())
uassert.Equal(t, Render(alice.String()), Render(s.String()), s.String())
uassert.Equal(t, Render(alice.String()), Render("account?address="+s.String()), s.String())
}
for _, s := range others {
uassert.False(t, strings.Contains(Render(s.String()), s.String()), "the page shows the address as the chain writes it")
}
uassert.False(t, Has(mixed))
uassert.Equal(t, "null", Lookup(mixed))
uassert.True(t, strings.HasPrefix(Render(mixed.String()), "# Not an address"))
// Bind: the proofs are those of the lower-case account.
bindSHA256, bindKeccak256 := first.signBind(5, "ML-DSA-65", testKey)
uassert.AbortsContains(t, cur, "no commit", func() {
Bind(cross(cur), mixed, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
})
uassert.False(t, IsUsed(loudQuiet, 5))
Bind(cross(cur), loudQuiet, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
for _, s := range spellings {
uassert.True(t, IsUsed(s, 5), s.String())
}
uassert.False(t, IsUsed(mixed, 5))
keyType, key, ok := Key(loud)
uassert.True(t, ok)
uassert.Equal(t, "ML-DSA-65", keyType)
uassert.Equal(t, string(testKey), string(key))
uassert.Equal(t, base64.StdEncoding.EncodeToString(testKey), KeyBase64(quiet))
uassert.Equal(t, "", KeyBase64(mixed))
uassert.AbortsContains(t, cur, "already used", func() {
Bind(cross(cur), alice, 5, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
})
// Authorize takes the spelling the chain writes and no other.
payload := []byte("withdraw 100ugnot")
authSHA256, authKeccak256 := first.signAuthorize(6, vault, payload)
testing.SetRealm(testing.NewCodeRealm(vault))
for _, s := range others {
spelled := s
uassert.AbortsContains(t, cur, "lower-case bech32", func() {
Authorize(cross(cur), spelled, 6, payload, authSHA256, authKeccak256)
})
}
uassert.False(t, IsUsed(alice, 6))
Authorize(cross(cur), alice, 6, payload, authSHA256, authKeccak256)
uassert.True(t, IsUsed(alice, 6))
// Rotate.
testing.SetRealm(relayer)
secondSHA256, secondKeccak256 := second.roots()
rotSHA256, rotKeccak256 := first.signRotate(7, second)
Rotate(cross(cur), quiet, 7, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
lookup := Lookup(loud)
uassert.True(t, strings.HasPrefix(lookup, `{"account":"`+alice.String()+`","rank":`), lookup)
uassert.True(t, strings.Contains(lookup, `"generation":1,`), lookup)
uassert.True(t, strings.Contains(lookup, `"rootSHA256":"`+secondSHA256+`"`), lookup)
uassert.True(t, strings.Contains(lookup, `"usedCount":0,`), lookup)
}
// TestSpentCommit spends every key of a commit: the page stops calling the
// account recoverable, and nothing can replace the commit any more.
func TestSpentCommit(cur realm, t *testing.T) {
const vault = "gno.land/r/someone/vault"
alice := testutils.TestAddress("spent-alice")
first := newHolder(alice, 0)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
testing.SetRealm(testing.NewCodeRealm(vault))
last := qrc.Leaves(qrc.MinHeight) - 1
for leaf := 0; leaf < last; leaf++ {
payload := []byte("approval " + strconv.Itoa(leaf))
a, b := first.signAuthorize(leaf, vault, payload)
Authorize(cross(cur), alice, leaf, payload, a, b)
}
page := Render(alice.String())
uassert.True(t, strings.Contains(page, "**Recoverable.**"), page)
uassert.True(t, strings.Contains(page, "| One-time keys | 64, 63 used |"), page)
payload := []byte("the last approval")
a, b := first.signAuthorize(last, vault, payload)
Authorize(cross(cur), alice, last, payload, a, b)
page = Render(alice.String())
uassert.False(t, strings.Contains(page, "Recoverable"), page)
uassert.True(t, strings.HasPrefix(page, "# "+alice.String()+"\n\n**No one-time key left.**"), page)
uassert.True(t, strings.Contains(page, "| One-time keys | 64, 64 used |"), page)
testing.SetRealm(relayer)
second := newHolder(alice, 1)
secondSHA256, secondKeccak256 := second.roots()
rotSHA256, rotKeccak256 := first.signRotate(last, second)
uassert.AbortsContains(t, cur, "already used", func() {
Rotate(cross(cur), alice, last, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
})
}
// TestKeyGeneration binds in one generation, rotates and binds again: a leaf
// number only means something with the generation it belongs to.
func TestKeyGeneration(cur realm, t *testing.T) {
alice := testutils.TestAddress("keygen-alice")
first := newHolder(alice, 0)
second := newHolder(alice, 1)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
testing.SetRealm(relayer)
bindSHA256, bindKeccak256 := first.signBind(10, "ML-DSA-65", testKey)
Bind(cross(cur), alice, 10, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
secondSHA256, secondKeccak256 := second.roots()
rotSHA256, rotKeccak256 := first.signRotate(11, second)
Rotate(cross(cur), alice, 11, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
lookup := Lookup(alice)
uassert.True(t, strings.Contains(lookup, `"generation":1,`), lookup)
uassert.True(t, strings.Contains(lookup, `"keyLeaf":10,"keyGeneration":0,`), lookup)
page := Render(alice.String())
uassert.True(t, strings.Contains(page, "with one-time key 10 of generation 0 |"), page)
uassert.False(t, IsUsed(alice, 10), "leaf 10 of the new trees is unspent")
other := []byte("a key bound in the second generation")
againSHA256, againKeccak256 := second.signBind(10, "ML-DSA-65", other)
Bind(cross(cur), alice, 10, "ML-DSA-65", other, againSHA256, againKeccak256)
lookup = Lookup(alice)
uassert.True(t, strings.Contains(lookup, `"keyLeaf":10,"keyGeneration":1,`), lookup)
uassert.True(t, strings.HasSuffix(lookup, `,"keyBinds":2}`), lookup)
}
// TestSpaces: gnoweb sends a space typed around the address in the form as
// '+', which the page ignores.
func TestSpaces(cur realm, t *testing.T) {
alice := testutils.TestAddress("spaces-alice")
page := Render(alice.String())
for _, path := range []string{
"account?address=+" + alice.String(),
"account?address=" + alice.String() + "+",
"account?address=++" + alice.String() + "++",
} {
uassert.Equal(t, page, Render(path), path)
}
}
// TestStaleRequest pins down what the documentation of Bind says: a signed
// request stays valid until its leaf is spent or the account rotates, and
// requests take effect in the order they land, not the order they were
// signed.
func TestStaleRequest(cur realm, t *testing.T) {
alice := testutils.TestAddress("stale-alice")
first := newHolder(alice, 0)
second := newHolder(alice, 1)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
testing.SetRealm(relayer)
earlier := []byte("the key alice signed for first")
later := []byte("the key alice signed for next")
earlierSHA256, earlierKeccak256 := first.signBind(1, "ML-DSA-65", earlier)
laterSHA256, laterKeccak256 := first.signBind(2, "ML-DSA-65", later)
Bind(cross(cur), alice, 2, "ML-DSA-65", later, laterSHA256, laterKeccak256)
Bind(cross(cur), alice, 1, "ML-DSA-65", earlier, earlierSHA256, earlierKeccak256)
_, key, _ := Key(alice)
uassert.Equal(t, string(earlier), string(key), "the request that lands last wins")
// A rotation is what retires a request still pending.
pendingSHA256, pendingKeccak256 := first.signBind(3, "ML-DSA-65", earlier)
secondSHA256, secondKeccak256 := second.roots()
rotSHA256, rotKeccak256 := first.signRotate(4, second)
Rotate(cross(cur), alice, 4, secondSHA256, secondKeccak256, qrc.MinHeight, rotSHA256, rotKeccak256)
uassert.AbortsContains(t, cur, "sha256 proof rejected", func() {
Bind(cross(cur), alice, 3, "ML-DSA-65", earlier, pendingSHA256, pendingKeccak256)
})
}
// TestRotateAcrossHeights moves a commit to a taller tree and back.
func TestRotateAcrossHeights(cur realm, t *testing.T) {
alice := testutils.TestAddress("heights-alice")
first := newHolder(alice, 0)
second := newHolderAt(alice, 1, qrc.MinHeight+1)
third := newHolder(alice, 2)
testing.SetRealm(testing.NewUserRealm(alice))
register(first, cur)
testing.SetRealm(relayer)
secondSHA256, secondKeccak256 := second.roots()
toSecondSHA256, toSecondKeccak256 := first.signRotate(5, second)
Rotate(cross(cur), alice, 5, secondSHA256, secondKeccak256, qrc.MinHeight+1, toSecondSHA256, toSecondKeccak256)
lookup := Lookup(alice)
uassert.True(t, strings.Contains(lookup, `"height":7,`), lookup)
uassert.True(t, strings.HasSuffix(lookup, `,"used":"`+strings.Repeat("00", 16)+`","usedCount":0}`), lookup)
// A leaf only the taller tree has.
bindSHA256, bindKeccak256 := second.signBind(100, "ML-DSA-65", testKey)
Bind(cross(cur), alice, 100, "ML-DSA-65", testKey, bindSHA256, bindKeccak256)
uassert.True(t, IsUsed(alice, 100))
thirdSHA256, thirdKeccak256 := third.roots()
toThirdSHA256, toThirdKeccak256 := second.signRotate(127, third)
Rotate(cross(cur), alice, 127, thirdSHA256, thirdKeccak256, qrc.MinHeight, toThirdSHA256, toThirdKeccak256)
lookup = Lookup(alice)
uassert.True(t, strings.Contains(lookup, `"generation":2,`), lookup)
uassert.True(t, strings.Contains(lookup, `"height":6,`), lookup)
uassert.True(t, strings.Contains(lookup, `"used":"`+strings.Repeat("00", 8)+`","usedCount":0,`), lookup)
uassert.True(t, strings.Contains(lookup, `"keyLeaf":100,"keyGeneration":1,`), lookup)
uassert.False(t, IsUsed(alice, 100), "leaf 100 is out of range again")
}
// TestLargest binds the largest key and the longest label Bind takes.
func TestLargest(cur realm, t *testing.T) {
alice := testutils.TestAddress("largest-alice")
h := newHolder(alice, 0)
testing.SetRealm(testing.NewUserRealm(alice))
register(h, cur)
testing.SetRealm(relayer)
key := make([]byte, MaxKeySize)
for i := range key {
key[i] = byte(i)
}
label := "K" + strings.Repeat("k", MaxKeyTypeSize-1)
proofSHA256, proofKeccak256 := h.signBind(0, label, key)
Bind(cross(cur), alice, 0, label, key, proofSHA256, proofKeccak256)
keyType, bound, ok := Key(alice)
uassert.True(t, ok)
uassert.Equal(t, label, keyType)
uassert.Equal(t, MaxKeySize, len(bound))
uassert.True(t, strings.Contains(Lookup(alice), `"keySize":65536,`))
}
views.gno
package qrcregistry
import (
"encoding/base64"
"encoding/hex"
"strconv"
"strings"
"time"
"gno.land/p/nym-rootlatch001/qrc/v1"
)
// Has reports whether account has a commit.
func Has(account address) bool {
return get(canonical(account)) != nil
}
// Count returns the number of accounts that hold a commit and, among them,
// the number that bound a new public key.
func Count() (accounts, withKey int) {
return commits.Size(), bound
}
// IsUsed reports whether one-time key number leaf of account was spent. It
// is false for an account without commit and for a leaf out of range. It
// only knows of keys spent by a transaction that succeeded: a signature made
// public in a failed one leaves its leaf unspent here, yet no wallet should
// sign with that leaf again.
func IsUsed(account address, leaf int) bool {
c := get(canonical(account))
if c == nil || leaf < 0 || leaf >= qrc.Leaves(c.height) {
return false
}
return c.isUsed(leaf)
}
// Key returns a copy of the public key last bound to account, with its
// label. ok is false if the account has no commit or never bound a key.
func Key(account address) (keyType string, key []byte, ok bool) {
c := get(canonical(account))
if c == nil || c.keyBinds == 0 {
return "", nil, false
}
return c.keyType, append([]byte(nil), c.key...), true
}
// KeyBase64 returns the public key last bound to account, base64 encoded, or
// an empty string if there is none.
func KeyBase64(account address) string {
c := get(canonical(account))
if c == nil || c.keyBinds == 0 {
return ""
}
return base64.StdEncoding.EncodeToString(c.key)
}
// Lookup returns what the registry holds about account as a JSON object, or
// the JSON value null if the account has no commit. It leaves out the roots
// of earlier generations.
//
// registeredAt, rotatedAt and keyAt are block heights, rotatedAt being 0
// before any rotation; registeredTime is in Unix seconds. "used" is the
// bitmap of the one-time keys spent in the current trees, in hexadecimal:
// key number n is spent when bit n%8, counting from the least significant,
// of byte n/8 is set. The key fields are only present once a key was bound;
// keyLeaf is a leaf of generation keyGeneration, which a later rotation
// retires. The key itself is served by KeyBase64.
func Lookup(account address) string {
account = canonical(account)
c := get(account)
if c == nil {
return "null"
}
var b strings.Builder
b.WriteString(`{"account":"` + account.String() + `"`)
b.WriteString(`,"rank":` + strconv.Itoa(c.rank))
b.WriteString(`,"registeredAt":` + strconv.FormatInt(c.registeredAt, 10))
b.WriteString(`,"registeredTime":` + strconv.FormatInt(c.registeredTime, 10))
b.WriteString(`,"generation":` + strconv.FormatUint(uint64(c.generation), 10))
b.WriteString(`,"rotatedAt":` + strconv.FormatInt(c.rotatedAt, 10))
b.WriteString(`,"height":` + strconv.Itoa(c.height))
b.WriteString(`,"rootSHA256":"` + hex.EncodeToString(c.rootSHA256[:]) + `"`)
b.WriteString(`,"rootKeccak256":"` + hex.EncodeToString(c.rootKeccak256[:]) + `"`)
b.WriteString(`,"used":"` + hex.EncodeToString(c.used) + `"`)
b.WriteString(`,"usedCount":` + strconv.Itoa(c.usedCount))
if c.keyBinds > 0 {
b.WriteString(`,"keyType":` + strconv.Quote(c.keyType))
b.WriteString(`,"keySize":` + strconv.Itoa(len(c.key)))
b.WriteString(`,"keySHA256":"` + hashHex(c.key) + `"`)
b.WriteString(`,"keyLeaf":` + strconv.Itoa(c.keyLeaf))
b.WriteString(`,"keyGeneration":` + strconv.FormatUint(uint64(c.keyGeneration), 10))
b.WriteString(`,"keyAt":` + strconv.FormatInt(c.keyAt, 10))
b.WriteString(`,"keyBinds":` + strconv.Itoa(c.keyBinds))
}
b.WriteString("}")
return b.String()
}
// Latest returns the accounts that registered last, newest first, at most
// latestKept of them, as a JSON array of objects. Each object holds the
// account, its rank, the height of its trees, the number of one-time keys
// spent in its current trees, its generation and, once a key was bound, the
// label of that key.
// The rest of what the registry holds about an account is served by Lookup.
func Latest() string {
var b strings.Builder
b.WriteString("[")
for i, account := range latest {
c := commits.Get(account).(*commit)
if i > 0 {
b.WriteString(",")
}
b.WriteString(`{"account":"` + account + `"`)
b.WriteString(`,"rank":` + strconv.Itoa(c.rank))
b.WriteString(`,"height":` + strconv.Itoa(c.height))
b.WriteString(`,"usedCount":` + strconv.Itoa(c.usedCount))
b.WriteString(`,"generation":` + strconv.FormatUint(uint64(c.generation), 10))
if c.keyBinds > 0 {
b.WriteString(`,"keyType":` + strconv.Quote(c.keyType))
}
b.WriteString("}")
}
b.WriteString("]")
return b.String()
}
// Render shows the registry: its home page for an empty path, the page of an
// account for "<address>" or "account?address=<address>".
func Render(path string) string {
route, query := path, ""
if i := strings.IndexByte(path, '?'); i >= 0 {
route, query = path[:i], path[i+1:]
}
switch route {
case "":
return renderHome()
case "account":
// A space typed around the address arrives as '+'.
return renderAccount(strings.Trim(queryValue(query, "address"), "+"))
}
return renderAccount(route)
}
func renderHome() string {
accounts, withKey := Count()
var b strings.Builder
b.WriteString("# Quantum Recovery Commits\n\n")
b.WriteString("Lets an account name a new public key in a way that does not rest on the signature scheme its wallet uses today.\n\n")
b.WriteString("An account registers here the roots of two Merkle trees of Lamport one-time keys, ")
b.WriteString("one hashed with SHA-256 and one with Keccak-256. Should its usual key ever be broken, ")
b.WriteString("these keys can still name a new public key for it. This realm only records that key: ")
b.WriteString("for it to sign for the account would take a change to the chain. ")
b.WriteString("It implements the registration step that the Quantum Proof Cryptography Roadmap of the ")
b.WriteString("[gno.land LAWS](https://github.com/gnolang/gno/blob/v1.8.1/docs/LAWS.md#quantum-proof-cryptography-roadmap) proposes.\n\n")
b.WriteString("**" + strconv.Itoa(accounts) + "** " + plural(accounts, "account holds", "accounts hold") + " a commit. ")
b.WriteString("**" + strconv.Itoa(withKey) + "** " + plural(withKey, "has", "have") + " bound a new public key.\n\n")
b.WriteString("## Look up an account\n\n")
b.WriteString("<gno-form path=\"account\">\n")
b.WriteString("\t<gno-input name=\"address\" type=\"text\" placeholder=\"Address (g1...)\" />\n")
b.WriteString("</gno-form>\n\n")
if accounts > 0 {
b.WriteString("## Latest registrations\n\n")
b.WriteString("| # | Account | One-time keys used | New public key |\n")
b.WriteString("|---|---|---|---|\n")
for _, account := range latest {
c := commits.Get(account).(*commit)
b.WriteString("| " + strconv.Itoa(c.rank))
b.WriteString(" | " + account)
b.WriteString(" | " + strconv.Itoa(c.usedCount) + " of " + strconv.Itoa(qrc.Leaves(c.height)))
b.WriteString(" | " + keySummary(c) + " |\n")
}
b.WriteString("\n")
}
b.WriteString("This realm is an independent prototype. It has no owner and nobody can change it.\n")
return b.String()
}
func renderAccount(input string) string {
account := canonical(address(input))
if !account.IsValid() {
return "# Not an address\n\nAn account page needs a valid address, such as `g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5`.\n"
}
var b strings.Builder
b.WriteString("# " + account.String() + "\n\n")
c := get(account)
if c == nil {
b.WriteString("**No commit.** This account has no commit in this registry. ")
b.WriteString("If its key were broken today, nothing here could tell its owner from the thief.\n")
return b.String()
}
if c.usedCount == qrc.Leaves(c.height) {
b.WriteString("**No one-time key left.** Every key of this commit was used: ")
b.WriteString("nothing can bind, rotate or authorize for this account any more. ")
} else {
b.WriteString("**Recoverable.** ")
}
b.WriteString("This account registered its commit at block ")
b.WriteString(strconv.FormatInt(c.registeredAt, 10))
b.WriteString(" (" + time.Unix(c.registeredTime, 0).UTC().Format("2006-01-02") + ")")
b.WriteString(", as account number " + strconv.Itoa(c.rank) + " of this registry.\n\n")
b.WriteString("| | |\n|---|---|\n")
b.WriteString("| SHA-256 root | `" + hex.EncodeToString(c.rootSHA256[:]) + "` |\n")
b.WriteString("| Keccak-256 root | `" + hex.EncodeToString(c.rootKeccak256[:]) + "` |\n")
b.WriteString("| One-time keys | " + strconv.Itoa(qrc.Leaves(c.height)) + ", " + strconv.Itoa(c.usedCount) + " used |\n")
b.WriteString("| Generation | " + strconv.FormatUint(uint64(c.generation), 10))
if c.rotatedAt > 0 {
b.WriteString(", rotated at block " + strconv.FormatInt(c.rotatedAt, 10))
}
b.WriteString(" |\n")
b.WriteString("| New public key | " + keySummary(c))
if c.keyBinds > 0 {
b.WriteString(", SHA-256 `" + hashHex(c.key) + "`")
b.WriteString(", bound at block " + strconv.FormatInt(c.keyAt, 10))
b.WriteString(" with one-time key " + strconv.Itoa(c.keyLeaf))
b.WriteString(" of generation " + strconv.FormatUint(uint64(c.keyGeneration), 10))
}
b.WriteString(" |\n")
return b.String()
}
// keySummary describes the key bound to c. The label is whatever the account
// chose, so it goes in a code span: nothing in it can then turn into a link
// or into formatting on a page that other people read.
func keySummary(c *commit) string {
if c.keyBinds == 0 {
return "none yet"
}
return "`" + c.keyType + "`, " + strconv.Itoa(len(c.key)) + " " + plural(len(c.key), "byte", "bytes")
}
func plural(n int, one, many string) string {
if n == 1 {
return one
}
return many
}
// queryValue returns the raw value of the first parameter called name in a
// URL query string, or "". Values are not unescaped: the only one read here
// is an address, which needs no escaping. A space typed around it arrives as
// '+', which the caller trims.
func queryValue(query, name string) string {
for _, part := range strings.Split(query, "&") {
if strings.HasPrefix(part, name+"=") {
return part[len(name)+1:]
}
}
return ""
}