// 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< 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 }