Playground
gnomod.toml
module = "gno.land/p/nym-rootlatch001/qrcsigner/v1" gno = "0.9" [addpkg] creator = "g14cryly8jxp54tjdaldvu6n2vsv5c4w0hwlt4fa" height = 1650628 max_deposit = "10000000ugnot"
signer.gno
// Package qrcsigner derives the one-time keys of a Quantum Recovery Commit
// from 32 bytes of entropy and signs with them.
//
// It is the reference signer: the key derivation written as running code,
// used by the tests of the registry, and by anyone who wants to check
// another implementation against it. Run it off-chain, with
// `gno test` or `gno run`. Never call it from a transaction: everything a
// transaction computes is public, and so would be the entropy.
//
// Nothing on chain depends on how secrets are derived. A commit made by any
// other signer verifies just the same, as long as its keys are Lamport keys
// arranged as package qrc describes.
//
// # Key derivation
//
// Each of the two trees first gets a seed of its own, computed with the hash
// function of the other tree:
//
// seed(SHA256) = Keccak256("QuantumRecoveryCommit/v1/seed/sha256" || 0x00 || entropy)
// seed(Keccak256) = SHA256( "QuantumRecoveryCommit/v1/seed/keccak256" || 0x00 || entropy)
//
// Each seed thus rests on the function of the other tree. Should one
// function ever be broken badly enough to walk back from the published
// hashes of its tree to that tree's seed, the entropy still sits behind the
// other function, and with it the seed of the other tree.
//
// From there on a tree only uses its own function. The secret number side
// (0 or 1) of digest bit number bit, in the one-time key number leaf, is
//
// info = "QuantumRecoveryCommit/v1/secret" || 0x00 || id.Bytes()
// || uint32 leaf || uint16 bit || uint8 side
// secret(SHA256) = HMAC-SHA256(key = seed, message = info)
// secret(Keccak256) = Keccak256(seed || info)
//
// with big-endian integers. Because info holds the commit ID, two commits
// never share a key, whatever the chain, registry, account or generation.
// The height is not part of info: a commit ID goes with a single height,
// since a kit derived for the same ID at another height shares its keys.
// A generation's keys are derived with the chain ID in force when the
// generation began; its messages carry the chain ID in force when they are
// sent.
package qrcsigner
import (
"crypto/keccak256"
"crypto/sha256"
"gno.land/p/nym-rootlatch001/qrc/v1"
)
// EntropySize is the size, in bytes, of the entropy a kit is derived from.
const EntropySize = 32
const (
seedLabel = qrc.Domain + "/seed/"
secretLabel = qrc.Domain + "/secret"
hmacBlockSize = 64 // block size of SHA-256
tailSize = 7 // uint32 leaf || uint16 bit || uint8 side
)
// Tree holds the one-time keys of one of the two commits of an account.
type Tree struct {
h qrc.Hash
height int
// Input buffers of the secret derivation. The last tailSize bytes of
// inner change with every secret, everything before them is fixed.
// SHA256: inner = (seed ^ ipad) || info, outer = (seed ^ opad) || inner digest
// Keccak256: inner = seed || info
inner []byte
outer []byte
// levels[0] holds the leaf hashes side by side, levels[height] the root.
levels [][]byte
}
// NewTree derives the tree of commit id built on hash function h. It computes
// every public key of the tree, 512 hashes per leaf.
func NewTree(h qrc.Hash, entropy []byte, id qrc.ID, height int) *Tree {
if !h.Valid() {
panic(qrc.ErrUnknownHash.Error())
}
if len(entropy) != EntropySize {
panic("qrcsigner: entropy must be 32 bytes long")
}
if height < qrc.MinHeight || height > qrc.MaxHeight {
panic(qrc.ErrHeight.Error())
}
seed := treeSeed(h, entropy)
info := append([]byte(secretLabel), 0x00)
info = append(info, id.Bytes()...)
t := &Tree{h: h, height: height}
if h == qrc.SHA256 {
t.inner = make([]byte, hmacBlockSize, hmacBlockSize+len(info)+tailSize)
t.outer = make([]byte, hmacBlockSize+qrc.HashSize)
for i := 0; i < hmacBlockSize; i++ {
var k byte
if i < len(seed) {
k = seed[i]
}
t.inner[i] = k ^ 0x36
t.outer[i] = k ^ 0x5c
}
} else {
t.inner = append(make([]byte, 0, len(seed)+len(info)+tailSize), seed[:]...)
}
t.inner = append(t.inner, info...)
t.inner = append(t.inner, make([]byte, tailSize)...)
t.build()
return t
}
// Hash returns the hash function the tree is built on.
func (t *Tree) Hash() qrc.Hash { return t.h }
// Height returns the height of the tree.
func (t *Tree) Height() int { return t.height }
// Root returns the commit: the root of the tree.
func (t *Tree) Root() [qrc.HashSize]byte {
var root [qrc.HashSize]byte
copy(root[:], t.levels[t.height])
return root
}
// Sign signs msg with one-time key number leaf and returns the proof
// qrc.Verify expects.
//
// A one-time key must sign a single message. Signing two different messages
// with the same leaf weakens the key, and a few more signatures give it away.
func (t *Tree) Sign(leaf int, msg []byte) []byte {
if leaf < 0 || leaf >= qrc.Leaves(t.height) {
panic(qrc.ErrLeafIndex.Error())
}
digest := t.h.Sum(msg)
proof := make([]byte, 0, qrc.ProofSize(t.height))
for i := 0; i < qrc.DigestBits; i++ {
bit := int(digest[i>>3]>>(7-uint(i&7))) & 1
for side := 0; side < 2; side++ {
// The secret on the side the digest bit selects, the hash of
// the secret on the other side.
value := t.secret(leaf, i, side)
if side != bit {
value = t.h.Sum(value[:])
}
proof = append(proof, value[:]...)
}
}
index := leaf
for level := 0; level < t.height; level++ {
sibling := index ^ 1
proof = append(proof, t.levels[level][sibling*qrc.HashSize:(sibling+1)*qrc.HashSize]...)
index >>= 1
}
return proof
}
// build computes every node of the tree.
func (t *Tree) build() {
leaves := qrc.Leaves(t.height)
level := make([]byte, leaves*qrc.HashSize)
pk := make([]byte, 1+qrc.PublicKeySize)
pk[0] = 0x00 // leaf prefix
for leaf := 0; leaf < leaves; leaf++ {
for i := 0; i < qrc.DigestBits; i++ {
for side := 0; side < 2; side++ {
secret := t.secret(leaf, i, side)
hashed := t.h.Sum(secret[:])
at := 1 + (2*i+side)*qrc.HashSize
copy(pk[at:at+qrc.HashSize], hashed[:])
}
}
leafHash := t.h.Sum(pk)
copy(level[leaf*qrc.HashSize:(leaf+1)*qrc.HashSize], leafHash[:])
}
t.levels = [][]byte{level}
var node [1 + 2*qrc.HashSize]byte
node[0] = 0x01 // inner node prefix
for len(level) > qrc.HashSize {
next := make([]byte, len(level)/2)
for at := 0; at < len(next); at += qrc.HashSize {
copy(node[1:], level[2*at:2*at+2*qrc.HashSize])
parent := t.h.Sum(node[:])
copy(next[at:at+qrc.HashSize], parent[:])
}
t.levels = append(t.levels, next)
level = next
}
}
// secret derives one secret of one one-time key.
func (t *Tree) secret(leaf, bit, side int) [qrc.HashSize]byte {
tail := t.inner[len(t.inner)-tailSize:]
tail[0] = byte(leaf >> 24)
tail[1] = byte(leaf >> 16)
tail[2] = byte(leaf >> 8)
tail[3] = byte(leaf)
tail[4] = byte(bit >> 8)
tail[5] = byte(bit)
tail[6] = byte(side)
if t.h == qrc.SHA256 {
digest := sha256.Sum256(t.inner)
copy(t.outer[hmacBlockSize:], digest[:])
return sha256.Sum256(t.outer)
}
return keccak256.Sum256(t.inner)
}
// treeSeed derives the seed of the tree built on h from the kit entropy,
// using the hash function of the other tree.
func treeSeed(h qrc.Hash, entropy []byte) [qrc.HashSize]byte {
in := append([]byte(seedLabel+h.String()), 0x00)
in = append(in, entropy...)
if h == qrc.SHA256 {
return keccak256.Sum256(in)
}
return sha256.Sum256(in)
}
// Kit holds both trees of a Quantum Recovery Commit.
type Kit struct {
sha256 *Tree
keccak256 *Tree
}
// New derives both trees of commit id from the kit entropy.
func New(entropy []byte, id qrc.ID, height int) *Kit {
return &Kit{
sha256: NewTree(qrc.SHA256, entropy, id, height),
keccak256: NewTree(qrc.Keccak256, entropy, id, height),
}
}
// Roots returns the two commits to register.
func (k *Kit) Roots() (rootSHA256, rootKeccak256 [qrc.HashSize]byte) {
return k.sha256.Root(), k.keccak256.Root()
}
// Sign signs msg with one-time key number leaf of both trees and returns the
// two proofs. See [Tree.Sign] about never signing twice with one leaf.
func (k *Kit) Sign(leaf int, msg []byte) (proofSHA256, proofKeccak256 []byte) {
return k.sha256.Sign(leaf, msg), k.keccak256.Sign(leaf, msg)
}
signer_test.gno
package qrcsigner
import (
"crypto/keccak256"
"crypto/sha256"
"encoding/hex"
"testing"
"gno.land/p/nym-rootlatch001/qrc/v1"
)
// The commit of the first test vector (see vectors/v1.json).
var testID = qrc.ID{
ChainID: "dev",
Registry: "gno.land/r/nym-rootlatch001/qrcregistry/v1",
Account: "g1jg8mtutu9khhfwc4nxmuhcpftf0pajdhfvsqf5",
Generation: 0,
}
func testEntropy() []byte {
entropy := make([]byte, EntropySize)
for i := range entropy {
entropy[i] = byte(i)
}
return entropy
}
func hexOf(b [qrc.HashSize]byte) string { return hex.EncodeToString(b[:]) }
// TestVector checks this implementation against the first test vector, which
// the Go build of this same code wrote and which the TypeScript library is
// tested against: three runtimes, one result.
func TestVector(t *testing.T) {
kit := New(testEntropy(), testID, qrc.MinHeight)
rootSHA256, rootKeccak256 := kit.Roots()
if got := hexOf(rootSHA256); got != "7d5cd56c59431c38474c804eef1069aa4b2bd10209ff415c5aaef9becc126d6c" {
t.Errorf("sha256 root = %s", got)
}
if got := hexOf(rootKeccak256); got != "eb2fd77bc5e8be3069f1269629c008abe17c0eed9d56a128c4dd0f451e359ed3" {
t.Errorf("keccak256 root = %s", got)
}
key, _ := hex.DecodeString("96a296d224f285c67bee93c30f8a309157f0daa35dc5b87e410b78630a09cfc7b413f47d13ee2fe6c845b2ee141af81d")
msg := qrc.BindMessage(testID, 0, "ML-DSA-65", key)
proofSHA256, proofKeccak256 := kit.Sign(0, msg)
if got := hexOf(sha256.Sum256(proofSHA256)); got != "5230669750006c8d68817925d27db1e9c865fee2f54372b3661e57e0aa04b93c" {
t.Errorf("sha256 of the sha256 proof = %s", got)
}
if got := hexOf(sha256.Sum256(proofKeccak256)); got != "06b65a004eb7ed29ee594da58893ea78281a845d6874004d155f4d06b240042e" {
t.Errorf("sha256 of the keccak256 proof = %s", got)
}
if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, 0, msg, proofSHA256); err != nil {
t.Errorf("sha256: %v", err)
}
if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, 0, msg, proofKeccak256); err != nil {
t.Errorf("keccak256: %v", err)
}
}
func TestSignVerify(t *testing.T) {
kit := New(testEntropy(), testID, qrc.MinHeight)
rootSHA256, rootKeccak256 := kit.Roots()
if rootSHA256 == rootKeccak256 {
t.Fatalf("the two commits are equal")
}
for _, leaf := range []int{0, 1, 42, 63} {
msg := qrc.BindMessage(testID, uint32(leaf), "ML-DSA-65", []byte("public key bytes"))
proofSHA256, proofKeccak256 := kit.Sign(leaf, msg)
if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, leaf, msg, proofSHA256); err != nil {
t.Fatalf("sha256, leaf %d: %v", leaf, err)
}
if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, leaf, msg, proofKeccak256); err != nil {
t.Fatalf("keccak256, leaf %d: %v", leaf, err)
}
// A proof is good for its own tree, leaf and message only.
if err := qrc.Verify(qrc.Keccak256, rootKeccak256, qrc.MinHeight, leaf, msg, proofSHA256); err != qrc.ErrMismatch {
t.Fatalf("leaf %d: sha256 proof against the keccak256 commit: %v", leaf, err)
}
if err := qrc.Verify(qrc.SHA256, rootSHA256, qrc.MinHeight, leaf^1, msg, proofSHA256); err != qrc.ErrMismatch {
t.Fatalf("leaf %d: proof accepted for its neighbour: %v", leaf, err)
}
}
}
// hmacSHA256 is HMAC as RFC 2104 writes it, for a key of at most 64 bytes.
func hmacSHA256(key, msg []byte) [qrc.HashSize]byte {
inner := make([]byte, 64, 64+len(msg))
outer := make([]byte, 64, 64+qrc.HashSize)
copy(inner, key)
copy(outer, key)
for i := 0; i < 64; i++ {
inner[i] ^= 0x36
outer[i] ^= 0x5c
}
digest := sha256.Sum256(append(inner, msg...))
return sha256.Sum256(append(outer, digest[:]...))
}
// TestDerivation recomputes secrets from the formulas of the package
// documentation, written out the long way, and compares them with what the
// trees use.
func TestDerivation(t *testing.T) {
entropy := testEntropy()
// RFC 4231, test case 2: the HMAC of this test is the standard one.
if got := hexOf(hmacSHA256([]byte("Jefe"), []byte("what do ya want for nothing?"))); got != "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" {
t.Fatalf("HMAC-SHA256 test case = %s", got)
}
seedSHA256 := keccak256.Sum256(append([]byte("QuantumRecoveryCommit/v1/seed/sha256\x00"), entropy...))
seedKeccak256 := sha256.Sum256(append([]byte("QuantumRecoveryCommit/v1/seed/keccak256\x00"), entropy...))
if seedSHA256 != treeSeed(qrc.SHA256, entropy) || seedKeccak256 != treeSeed(qrc.Keccak256, entropy) {
t.Fatalf("tree seeds differ from their definition")
}
treeSHA256 := NewTree(qrc.SHA256, entropy, testID, qrc.MinHeight)
treeKeccak256 := NewTree(qrc.Keccak256, entropy, testID, qrc.MinHeight)
for _, tc := range []struct{ leaf, bit, side int }{
{0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {1, 0, 0},
{63, 255, 1}, {37, 128, 0}, {5, 255, 0}, {62, 7, 1},
} {
info := append([]byte("QuantumRecoveryCommit/v1/secret\x00"), testID.Bytes()...)
info = append(info,
byte(tc.leaf>>24), byte(tc.leaf>>16), byte(tc.leaf>>8), byte(tc.leaf),
byte(tc.bit>>8), byte(tc.bit),
byte(tc.side))
if want := hmacSHA256(seedSHA256[:], info); treeSHA256.secret(tc.leaf, tc.bit, tc.side) != want {
t.Errorf("sha256 secret (%d, %d, %d) differs from its definition", tc.leaf, tc.bit, tc.side)
}
if want := keccak256.Sum256(append(seedKeccak256[:], info...)); treeKeccak256.secret(tc.leaf, tc.bit, tc.side) != want {
t.Errorf("keccak256 secret (%d, %d, %d) differs from its definition", tc.leaf, tc.bit, tc.side)
}
}
}
// TestProofLayout checks a proof against the description of package qrc:
// in every pair, the secret on the side the digest bit selects and the hash
// of the other secret, then the siblings up to the root.
func TestProofLayout(t *testing.T) {
const leaf = 21
msg := []byte("a message")
for _, h := range []qrc.Hash{qrc.SHA256, qrc.Keccak256} {
tree := NewTree(h, testEntropy(), testID, qrc.MinHeight)
if tree.Hash() != h || tree.Height() != qrc.MinHeight {
t.Fatalf("%s: tree reports %s, height %d", h, tree.Hash(), tree.Height())
}
proof := tree.Sign(leaf, msg)
if len(proof) != qrc.ProofSize(qrc.MinHeight) {
t.Fatalf("%s: proof of %d bytes", h, len(proof))
}
digest := h.Sum(msg)
zeros, ones := 0, 0
for bit := 0; bit < qrc.DigestBits; bit++ {
selected := int(digest[bit/8]>>(7-uint(bit%8))) & 1
if selected == 0 {
zeros++
} else {
ones++
}
for side := 0; side < 2; side++ {
want := tree.secret(leaf, bit, side)
if side != selected {
want = h.Sum(want[:])
}
at := (2*bit + side) * qrc.HashSize
if string(proof[at:at+qrc.HashSize]) != string(want[:]) {
t.Fatalf("%s: bit %d, side %d holds the wrong value", h, bit, side)
}
}
}
if zeros == 0 || ones == 0 {
t.Fatalf("%s: the digest has a single bit value, pick another message", h)
}
// The path: leaf 21 is 010101 in binary, so its siblings sit to the
// left, right, left, right, left, right of the nodes on the way up.
node := leaf
for level := 0; level < qrc.MinHeight; level++ {
sibling := node ^ 1
want := tree.levels[level][sibling*qrc.HashSize : (sibling+1)*qrc.HashSize]
at := qrc.SignatureSize + level*qrc.HashSize
if string(proof[at:at+qrc.HashSize]) != string(want) {
t.Fatalf("%s: wrong sibling at level %d", h, level)
}
node >>= 1
}
}
}
// TestCommitsAreSeparate checks that nothing but the same entropy and the
// same commit ID leads to the same keys.
func TestCommitsAreSeparate(t *testing.T) {
base := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight).Root()
if again := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight).Root(); again != base {
t.Fatalf("the same entropy and ID gave two different commits")
}
seen := map[string]string{hexOf(base): "base"}
check := func(name string, entropy []byte, id qrc.ID) {
root := hexOf(NewTree(qrc.SHA256, entropy, id, qrc.MinHeight).Root())
if other, ok := seen[root]; ok {
t.Errorf("%s and %s have the same commit", name, other)
}
seen[root] = name
}
entropy := testEntropy()
entropy[31] ^= 1
check("another entropy", entropy, testID)
id := testID
id.ChainID = "onyx-1"
check("another chain", testEntropy(), id)
id = testID
id.Registry = "gno.land/r/other/qrcregistry/v1"
check("another registry", testEntropy(), id)
id = testID
id.Account = "g1us8428u2a5satrlxzagqqa5m6vmuze025anjlj"
check("another account", testEntropy(), id)
id = testID
id.Generation = 1
check("another generation", testEntropy(), id)
// The two trees of one commit share no secret either.
a := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight)
b := NewTree(qrc.Keccak256, testEntropy(), testID, qrc.MinHeight)
if a.secret(0, 0, 0) == b.secret(0, 0, 0) {
t.Errorf("the two trees share a secret")
}
}
func TestBadArguments(t *testing.T) {
for name, f := range map[string]func(){
"unknown hash": func() { NewTree(qrc.Hash(9), testEntropy(), testID, qrc.MinHeight) },
"short entropy": func() { NewTree(qrc.SHA256, testEntropy()[:31], testID, qrc.MinHeight) },
"long entropy": func() { NewTree(qrc.SHA256, append(testEntropy(), 0), testID, qrc.MinHeight) },
"no entropy": func() { NewTree(qrc.SHA256, nil, testID, qrc.MinHeight) },
"height 5": func() { NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight-1) },
"height 17": func() { NewTree(qrc.SHA256, testEntropy(), testID, qrc.MaxHeight+1) },
} {
if !panics(f) {
t.Errorf("%s: accepted", name)
}
}
tree := NewTree(qrc.SHA256, testEntropy(), testID, qrc.MinHeight)
for _, leaf := range []int{-1, 64, 1 << 20} {
if !panics(func() { tree.Sign(leaf, []byte("m")) }) {
t.Errorf("leaf %d: signed", leaf)
}
}
}
func panics(f func()) (panicked bool) {
defer func() {
if recover() != nil {
panicked = true
}
}()
f()
return false
}