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.

Playground

doc.gno

// Package qrc verifies Quantum Recovery Commits.
//
// The gno.land LAWS ("Quantum Proof Cryptography Roadmap", user accounts) ask
// for a protocol that registers each account with
//
//	two Merkle tree hash commits of at least 64 distinct Lamport signature
//	public keys with one commit using only the sha256 hash function and the
//	other commit using a different hash function family such as sha3
//	(Quantum Recovery Commit) that can be used to securely register/sign-for
//	at least 64 new arbitrary (e.g. quantum-proof) public key bytes of any
//	length determined in the future (e.g. after "D-day") for each commit.
//
// This package is the stateless half of such a protocol. It knows how to
// check that a message was signed by one of the one-time keys a commit
// stands for, and how the signed messages are laid out. It holds no state
// and no secret: keeping the commits and enforcing that every key signs at
// most once is the job of a realm.
//
// # Construction
//
// Everything below exists twice, once per hash function H. The two copies
// never share a hash call, so a break of one function leaves the other
// commit intact.
//
// A Lamport key has one pair of 32-byte secrets per bit of a 256-bit digest.
// Its public key is the 512 hashes H(secret), pair after pair:
//
//	PK = H(s[0][0]) || H(s[0][1]) || H(s[1][0]) || ... || H(s[255][1])
//
// To sign a message, the signer hashes it with H. Bit number i of the digest,
// counting from the most significant bit of byte 0, selects one secret of
// pair i: s[i][0] if the bit is 0, s[i][1] if it is 1. The signature is the
// public key in which the hash of every selected secret is replaced by the
// secret itself:
//
//	signature = PK, with H(s[i][bit i]) replaced by s[i][bit i] for all i
//
// It is as long as the public key. A verifier hashes the 256 selected values
// where they stand and gets the public key back, without ever having seen
// it: a signature made with another key, or for another digest, gives back
// other bytes.
//
// The commit is the root of an RFC 6962 Merkle tree whose leaves are the
// public keys. It is the tree gno.land builds over its own blocks, the
// simple Merkle tree of Tendermint, for a number of leaves that is a power
// of two:
//
//	leaf  = H(0x00 || PK)
//	inner = H(0x01 || left || right)
//
// A proof is a signature followed by the sibling hashes on the way from the
// leaf to the root, bottom first. See [Verify].
//
// # Cost
//
// Checking a proof takes one hash of the message, whose cost grows with its
// length, then 257 hash calls for the signature, one of them over the 16385
// bytes of a leaf, and one per tree level. A proof is 16384 bytes plus 32
// per level: 16576 bytes for 64 keys, 16896 for 65536.
//
// # One-time keys
//
// A Lamport key may sign a single message. Every further message signed with
// it reveals both secrets of more of its pairs and makes a forgery cheaper: a
// few such signatures make it easy. [Verify] cannot detect that. Whoever
// stores a commit must remember which leaves were used and refuse them
// forever, and a signer must treat a leaf as used as soon as a signature made
// with it leaves its hands, even if the transaction that carried it failed.
package qrc

gas_test.gno

package qrc

import "testing"

// The tests below tell what one call to Verify costs in gas. Run
//
//	gno test -v -run TestGas ./qrc
//
// and, for each hash function, subtract the gas of the Setup test from the
// gas of the Verify test, then divide by gasRuns. The figure covers the
// virtual machine alone: a transaction also pays for its size and for what
// it stores.
const (
	gasRuns   = 10
	gasHeight = MinHeight
	gasLeaf   = 37
)

var gasMessage = []byte("bind this key to my account")

func gasVerify(t *testing.T, h Hash, runs int) {
	root, proof := testProof(h, gasHeight, gasLeaf, gasMessage)
	for i := 0; i < runs; i++ {
		if err := Verify(h, root, gasHeight, gasLeaf, gasMessage, proof); err != nil {
			t.Fatalf("%s: %v", h, err)
		}
	}
}

func TestGasSetupSHA256(t *testing.T)     { gasVerify(t, SHA256, 0) }
func TestGasVerifySHA256(t *testing.T)    { gasVerify(t, SHA256, gasRuns) }
func TestGasSetupKeccak256(t *testing.T)  { gasVerify(t, Keccak256, 0) }
func TestGasVerifyKeccak256(t *testing.T) { gasVerify(t, Keccak256, gasRuns) }

gnomod.toml

module = "gno.land/p/nym-rootlatch001/qrc/v1"
gno = "0.9"

[addpkg]
  creator = "g14cryly8jxp54tjdaldvu6n2vsv5c4w0hwlt4fa"
  height = 1650609
  max_deposit = "14000000ugnot"

hash.gno

package qrc

import (
	"crypto/keccak256"
	"crypto/sha256"
)

// HashSize is the output size, in bytes, of both hash functions.
const HashSize = 32

// Hash names the hash function a commit is built on. A commit uses its
// function for everything: public keys, message digests and tree nodes.
type Hash uint8

const (
	// SHA256 is SHA-256 of FIPS 180-4, the SHA-2 family.
	SHA256 Hash = 1
	// Keccak256 is Keccak-256 with the original padding, as used by the
	// EVM. It is the same sponge and permutation as SHA3-256 of FIPS 202
	// and differs from it only in the padding byte.
	Keccak256 Hash = 2
)

// Valid reports whether h names a supported hash function.
func (h Hash) Valid() bool {
	return h == SHA256 || h == Keccak256
}

// String returns the name of the hash function.
func (h Hash) String() string {
	switch h {
	case SHA256:
		return "sha256"
	case Keccak256:
		return "keccak256"
	}
	return "unknown"
}

// Sum returns the digest of data. It panics if h is not [Valid].
func (h Hash) Sum(data []byte) [HashSize]byte {
	return h.function()(data)
}

// function returns the function h names. Code that hashes in a loop fetches
// it once instead of calling Sum, which looks it up every time.
func (h Hash) function() func([]byte) [HashSize]byte {
	switch h {
	case SHA256:
		return sha256.Sum256
	case Keccak256:
		return keccak256.Sum256
	}
	panic("qrc: unknown hash function")
}

helpers_test.gno

package qrc

// The tests of this package sign with the throwaway signer below instead of
// package qrcsigner. Its secrets come from a counter, which is as good as
// anything to a verifier: no proof tells how its secrets were chosen. It also
// builds whole trees, level by level, where Verify only walks one path. The
// two meet at the root or the test fails.

// testKey is one Lamport one-time key.
type testKey struct {
	h    Hash
	seed byte
}

func (k testKey) secret(bit, side int) [HashSize]byte {
	return k.h.Sum([]byte{'k', k.seed, byte(bit >> 8), byte(bit), byte(side)})
}

// public returns the public key: the hash of secret 0 then of secret 1, for
// every digest bit in turn.
func (k testKey) public() []byte {
	pk := make([]byte, 0, PublicKeySize)
	for bit := 0; bit < DigestBits; bit++ {
		for side := 0; side < 2; side++ {
			secret := k.secret(bit, side)
			hashed := k.h.Sum(secret[:])
			pk = append(pk, hashed[:]...)
		}
	}
	return pk
}

// sign returns the signature of msg. For every bit of its digest, most
// significant bit of the first byte first, it holds two values: the secret
// of the side the bit selects, and the hash of the secret of the other side,
// side 0 before side 1.
func (k testKey) sign(msg []byte) []byte {
	digest := k.h.Sum(msg)
	sig := make([]byte, 0, SignatureSize)
	for bit := 0; bit < DigestBits; bit++ {
		selected := int(digest[bit/8]>>(7-uint(bit%8))) & 1
		for side := 0; side < 2; side++ {
			value := k.secret(bit, side)
			if side != selected {
				value = k.h.Sum(value[:])
			}
			sig = append(sig, value[:]...)
		}
	}
	return sig
}

// testTree is a complete Merkle tree. items holds what the leaves stand for,
// levels[0] the leaves, and the last level the root alone.
type testTree struct {
	h      Hash
	items  [][]byte
	levels [][][HashSize]byte
}

// newTestTree builds the tree of the given height in which the leaves named
// in keys stand for real one-time keys. Every other leaf stands for three
// bytes of filler.
func newTestTree(h Hash, height int, keys map[int]testKey) *testTree {
	tree := &testTree{h: h, items: make([][]byte, Leaves(height))}
	for i := range tree.items {
		tree.items[i] = []byte{'f', byte(i >> 8), byte(i)}
	}
	for leaf, key := range keys {
		tree.items[leaf] = key.public()
	}

	level := make([][HashSize]byte, len(tree.items))
	for i, item := range tree.items {
		level[i] = h.Sum(append([]byte{0x00}, item...))
	}
	tree.levels = [][][HashSize]byte{level}
	for len(level) > 1 {
		next := make([][HashSize]byte, len(level)/2)
		for i := range next {
			node := append([]byte{0x01}, level[2*i][:]...)
			node = append(node, level[2*i+1][:]...)
			next[i] = h.Sum(node)
		}
		tree.levels = append(tree.levels, next)
		level = next
	}
	return tree
}

func (t *testTree) root() [HashSize]byte {
	return t.levels[len(t.levels)-1][0]
}

// path returns the siblings met on the way from leaf to the root.
func (t *testTree) path(leaf int) []byte {
	var path []byte
	for level := 0; level < len(t.levels)-1; level++ {
		sibling := t.levels[level][(leaf>>uint(level))^1]
		path = append(path, sibling[:]...)
	}
	return path
}

// testProof signs msg with a fresh key placed at leaf of a tree of the given
// height, and returns the root of that tree with the proof.
func testProof(h Hash, height, leaf int, msg []byte) (root [HashSize]byte, proof []byte) {
	key := testKey{h, byte(leaf)}
	tree := newTestTree(h, height, map[int]testKey{leaf: key})
	return tree.root(), append(key.sign(msg), tree.path(leaf)...)
}

var bothHashes = []Hash{SHA256, Keccak256}

message.gno

package qrc

// Domain opens every message signed with a commit key, so that such a
// signature can never be mistaken for anything else.
const Domain = "QuantumRecoveryCommit/v1"

// Action tells what a signed message asks for.
type Action uint8

const (
	// ActionBind registers new public key bytes for the account.
	ActionBind Action = 1
	// ActionRotate replaces the account's commit by a new one.
	ActionRotate Action = 2
	// ActionAuthorize approves a payload defined by another realm.
	ActionAuthorize Action = 3
)

// ID identifies one commit: the n-th commit of an account, in one registry,
// on one chain. Messages carry it so that a signature made for one commit is
// worthless for any other, and signers derive their keys from it so that no
// one-time key is ever shared between two commits.
type ID struct {
	ChainID    string // chain the registry runs on
	Registry   string // package path of the realm that stores the commit
	Account    string // address of the account, as the chain writes it (lower-case bech32)
	Generation uint32 // number of times the account replaced its commit
}

// Bytes returns the canonical encoding of id: each string preceded by its
// length as a big-endian uint16, then the generation as a big-endian uint32.
func (id ID) Bytes() []byte {
	b := make([]byte, 0, 10+len(id.ChainID)+len(id.Registry)+len(id.Account))
	b = appendString(b, id.ChainID)
	b = appendString(b, id.Registry)
	b = appendString(b, id.Account)
	return appendUint32(b, id.Generation)
}

// BindMessage returns the bytes to sign, with one-time key number leaf, in
// order to register key as the new public key of the account. keyType is a
// free label naming the scheme key belongs to.
//
//	header || uint16 len(keyType) || keyType || uint32 len(key) || key
//
// The header common to all messages is
//
//	Domain || 0x00 || action || id.Bytes() || uint32 leaf
//
// All integers are big-endian. Every variable-length field carries its
// length, so two different requests never produce the same bytes.
func BindMessage(id ID, leaf uint32, keyType string, key []byte) []byte {
	b := header(id, leaf, ActionBind, 6+len(keyType)+len(key))
	b = appendString(b, keyType)
	return appendBytes(b, key)
}

// RotateMessage returns the bytes to sign, with one-time key number leaf, in
// order to replace the commit id by a new one made of the two given roots
// and tree height.
//
//	header || rootSHA256 || rootKeccak256 || uint8 height
func RotateMessage(id ID, leaf uint32, rootSHA256, rootKeccak256 [HashSize]byte, height int) []byte {
	if height < MinHeight || height > MaxHeight {
		panic(ErrHeight.Error())
	}
	b := header(id, leaf, ActionRotate, 2*HashSize+1)
	b = append(b, rootSHA256[:]...)
	b = append(b, rootKeccak256[:]...)
	return append(b, byte(height))
}

// AuthorizeMessage returns the bytes to sign, with one-time key number leaf,
// in order to approve payload on behalf of the account. app is the package
// path of the realm the approval is meant for; no other realm can use it.
//
//	header || uint16 len(app) || app || uint32 len(payload) || payload
func AuthorizeMessage(id ID, leaf uint32, app string, payload []byte) []byte {
	b := header(id, leaf, ActionAuthorize, 6+len(app)+len(payload))
	b = appendString(b, app)
	return appendBytes(b, payload)
}

func header(id ID, leaf uint32, action Action, bodySize int) []byte {
	idBytes := id.Bytes()
	b := make([]byte, 0, len(Domain)+2+len(idBytes)+4+bodySize)
	b = append(b, []byte(Domain)...)
	b = append(b, 0x00, byte(action))
	b = append(b, idBytes...)
	return appendUint32(b, leaf)
}

func appendString(b []byte, s string) []byte {
	if len(s) > 0xffff {
		panic("qrc: string too long")
	}
	b = append(b, byte(len(s)>>8), byte(len(s)))
	return append(b, []byte(s)...)
}

func appendBytes(b []byte, p []byte) []byte {
	if uint64(len(p)) > 0xffffffff {
		panic("qrc: payload too long")
	}
	b = appendUint32(b, uint32(len(p)))
	return append(b, p...)
}

func appendUint32(b []byte, v uint32) []byte {
	return append(b, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
}

message_test.gno

package qrc

import (
	"strings"
	"testing"
)

var messageID = ID{
	ChainID:    "dev",
	Registry:   "gno.land/r/x/reg/v1",
	Account:    "g1abc",
	Generation: 7,
}

// The encoding of messageID, written out by hand.
const messageIDBytes = "\x00\x03dev" + "\x00\x13gno.land/r/x/reg/v1" + "\x00\x05g1abc" + "\x00\x00\x00\x07"

func TestIDBytes(t *testing.T) {
	if got := string(messageID.Bytes()); got != messageIDBytes {
		t.Errorf("got %q, want %q", got, messageIDBytes)
	}
	if got := string(ID{}.Bytes()); got != "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" {
		t.Errorf("empty ID: got %q", got)
	}

	// Moving a character from one field to the next changes the encoding.
	a := ID{ChainID: "ab", Registry: "c", Account: "d"}
	b := ID{ChainID: "a", Registry: "bc", Account: "d"}
	c := ID{ChainID: "a", Registry: "b", Account: "cd"}
	if string(a.Bytes()) == string(b.Bytes()) || string(b.Bytes()) == string(c.Bytes()) {
		t.Errorf("two different IDs have the same encoding")
	}

	// The generation uses its four bytes, most significant first.
	id := messageID
	id.Generation = 0x01020304
	if got := string(id.Bytes()); !strings.HasSuffix(got, "\x01\x02\x03\x04") {
		t.Errorf("generation encoded as %q", got[len(got)-4:])
	}
}

func TestBindMessage(t *testing.T) {
	want := "QuantumRecoveryCommit/v1" + "\x00" + "\x01" + messageIDBytes +
		"\x00\x00\x01\x02" + // leaf 258
		"\x00\x09ML-DSA-65" +
		"\x00\x00\x00\x03\xaa\xbb\xcc"
	got := string(BindMessage(messageID, 258, "ML-DSA-65", []byte{0xaa, 0xbb, 0xcc}))
	if got != want {
		t.Errorf("got  %q\nwant %q", got, want)
	}

	// The label and the key cannot trade bytes.
	a := BindMessage(messageID, 1, "ab", []byte("c"))
	b := BindMessage(messageID, 1, "a", []byte("bc"))
	if string(a) == string(b) {
		t.Errorf("two different requests have the same message")
	}
}

func TestRotateMessage(t *testing.T) {
	var rootSHA256, rootKeccak256 [HashSize]byte
	for i := range rootSHA256 {
		rootSHA256[i] = byte(i)
		rootKeccak256[i] = byte(0xff - i)
	}
	want := "QuantumRecoveryCommit/v1" + "\x00" + "\x02" + messageIDBytes +
		"\x00\x00\x00\x3f" + // leaf 63
		string(rootSHA256[:]) + string(rootKeccak256[:]) +
		"\x10" // height 16
	got := string(RotateMessage(messageID, 63, rootSHA256, rootKeccak256, 16))
	if got != want {
		t.Errorf("got  %q\nwant %q", got, want)
	}

	// The two roots are not interchangeable.
	swapped := string(RotateMessage(messageID, 63, rootKeccak256, rootSHA256, 16))
	if swapped == got {
		t.Errorf("swapping the roots leaves the message unchanged")
	}

	for _, height := range []int{MinHeight - 1, MaxHeight + 1, -1, 256 + MinHeight} {
		if !panics(func() { RotateMessage(messageID, 0, rootSHA256, rootKeccak256, height) }) {
			t.Errorf("height %d accepted", height)
		}
	}
}

func TestAuthorizeMessage(t *testing.T) {
	want := "QuantumRecoveryCommit/v1" + "\x00" + "\x03" + messageIDBytes +
		"\x00\x00\x00\x00" + // leaf 0
		"\x00\x12gno.land/r/x/vault" +
		"\x00\x00\x00\x08withdraw"
	got := string(AuthorizeMessage(messageID, 0, "gno.land/r/x/vault", []byte("withdraw")))
	if got != want {
		t.Errorf("got  %q\nwant %q", got, want)
	}

	// An empty payload is a message like any other.
	empty := string(AuthorizeMessage(messageID, 0, "gno.land/r/x/vault", nil))
	if !strings.HasSuffix(empty, "vault\x00\x00\x00\x00") {
		t.Errorf("empty payload encoded as %q", empty)
	}
}

// TestMessagesAreDistinct checks that no request can pass for another one:
// the same fields under two actions, two chains, two registries, two
// accounts, two generations or two leaves never give the same bytes.
func TestMessagesAreDistinct(t *testing.T) {
	seen := map[string]string{}
	add := func(name string, msg []byte) {
		if other, ok := seen[string(msg)]; ok {
			t.Errorf("%s and %s have the same message", name, other)
		}
		seen[string(msg)] = name
	}

	payload := []byte("payload")
	var rootA, rootB [HashSize]byte
	rootB[0] = 1
	ids := map[string]ID{"base": messageID}
	id := messageID
	id.ChainID = "test"
	ids["chain"] = id
	id = messageID
	id.Registry = "gno.land/r/y/reg/v1"
	ids["registry"] = id
	id = messageID
	id.Account = "g1abd"
	ids["account"] = id
	id = messageID
	id.Generation = 8
	ids["generation"] = id

	for name, id := range ids {
		for _, leaf := range []uint32{0, 1} {
			suffix := " (" + name + ", leaf " + string(rune('0'+leaf)) + ")"
			add("bind"+suffix, BindMessage(id, leaf, "app", payload))
			add("authorize"+suffix, AuthorizeMessage(id, leaf, "app", payload))
			add("rotate"+suffix, RotateMessage(id, leaf, rootA, rootB, MinHeight))
		}
	}
	if len(seen) != 30 {
		t.Errorf("%d distinct messages, want 30", len(seen))
	}
}

func panics(f func()) (panicked bool) {
	defer func() {
		if recover() != nil {
			panicked = true
		}
	}()
	f()
	return false
}

verify.gno

package qrc

import "errors"

const (
	// DigestBits is the number of digest bits a Lamport key signs, and so
	// the number of secret pairs in a key.
	DigestBits = HashSize * 8

	// PublicKeySize is the size of a Lamport public key: two hashes per
	// digest bit.
	PublicKeySize = DigestBits * 2 * HashSize

	// SignatureSize is the size of a Lamport signature: the public key with
	// one hash of each pair replaced by the secret it is the hash of.
	SignatureSize = PublicKeySize

	// MinHeight is the smallest tree a commit may use. It holds 64 one-time
	// keys, the minimum the LAWS ask for.
	MinHeight = 6

	// MaxHeight is the largest tree a commit may use, 65536 one-time keys.
	MaxHeight = 16
)

// Domain separation of tree nodes, as in RFC 6962. A Lamport secret is hashed
// without prefix: it is exactly HashSize bytes long, a length neither a leaf
// nor an inner node input can have.
const (
	leafPrefix  = 0x00
	innerPrefix = 0x01
)

var (
	ErrUnknownHash = errors.New("qrc: unknown hash function")
	ErrHeight      = errors.New("qrc: tree height out of range")
	ErrLeafIndex   = errors.New("qrc: leaf index out of range")
	ErrProofSize   = errors.New("qrc: proof has the wrong size")
	ErrMismatch    = errors.New("qrc: proof does not match the commit")
)

// ProofSize returns the exact size, in bytes, of a proof for a tree of the
// given height: one signature and one sibling hash per tree level.
func ProofSize(height int) int {
	return SignatureSize + height*HashSize
}

// Leaves returns the number of one-time keys in a tree of the given height.
func Leaves(height int) int {
	return 1 << uint(height)
}

// Verify checks a proof against a commit.
//
// It returns nil when proof shows that msg was signed by the Lamport key
// stored at leaf of the Merkle tree of the given height whose root is root,
// everything hashed with h. The proof layout is described in the package
// documentation; its size must be exactly [ProofSize](height).
//
// Verify is a pure function of its arguments. It does not know whether the
// leaf has signed before: see the package documentation on one-time keys.
func Verify(h Hash, root [HashSize]byte, height int, leaf int, msg []byte, proof []byte) error {
	if !h.Valid() {
		return ErrUnknownHash
	}
	if height < MinHeight || height > MaxHeight {
		return ErrHeight
	}
	if leaf < 0 || leaf >= Leaves(height) {
		return ErrLeafIndex
	}
	if len(proof) != ProofSize(height) {
		return ErrProofSize
	}
	sum := h.function()
	node := recoverLeaf(sum, sum(msg), proof)
	if climb(sum, node, leaf, height, proof) != root {
		return ErrMismatch
	}
	return nil
}

// recoverLeaf returns the leaf hash of the one public key under which the
// first SignatureSize bytes of proof are a Lamport signature of digest.
//
// A signature is the public key with, in every pair, the hash selected by the
// digest bit replaced by its secret. Hashing that secret in place therefore
// turns the signature back into the public key: one copy of the signature,
// then one hash and one 32-byte copy per digest bit. The loop is written for
// the gas meter, where every built-in call has a fixed price well above that
// of a SHA-256 of 32 bytes.
func recoverLeaf(sum func([]byte) [HashSize]byte, digest [HashSize]byte, proof []byte) [HashSize]byte {
	buf := make([]byte, 1+PublicKeySize)
	buf[0] = leafPrefix
	copy(buf[1:], proof[:SignatureSize])

	at := 1 // start of the pair of the current digest bit
	for _, d := range digest {
		for mask := byte(0x80); mask != 0; mask >>= 1 {
			slot := at
			if d&mask != 0 {
				slot += HashSize
			}
			secret := buf[slot : slot+HashSize]
			opened := sum(secret)
			copy(secret, opened[:])
			at += 2 * HashSize
		}
	}
	return sum(buf)
}

// climb folds node, the leaf number index of a tree of the given height, with
// the sibling hashes that follow the signature in proof, bottom first, and
// returns the root they lead to.
func climb(sum func([]byte) [HashSize]byte, node [HashSize]byte, index, height int, proof []byte) [HashSize]byte {
	var buf [1 + 2*HashSize]byte
	buf[0] = innerPrefix
	left, right := buf[1:1+HashSize], buf[1+HashSize:]

	at := SignatureSize
	for level := 0; level < height; level++ {
		sibling := proof[at : at+HashSize]
		if index&1 == 0 {
			copy(left, node[:])
			copy(right, sibling)
		} else {
			copy(left, sibling)
			copy(right, node[:])
		}
		node = sum(buf[:])
		index >>= 1
		at += HashSize
	}
	return node
}

verify_test.gno

package qrc

import (
	"crypto/merkle"
	"encoding/hex"
	"testing"
)

func TestSizes(t *testing.T) {
	for _, tc := range []struct {
		name      string
		got, want int
	}{
		{"HashSize", HashSize, 32},
		{"DigestBits", DigestBits, 256},
		{"PublicKeySize", PublicKeySize, 16384},
		{"SignatureSize", SignatureSize, 16384},
		{"MinHeight", MinHeight, 6},
		{"MaxHeight", MaxHeight, 16},
		{"Leaves(MinHeight)", Leaves(MinHeight), 64},
		{"Leaves(MaxHeight)", Leaves(MaxHeight), 65536},
		{"ProofSize(MinHeight)", ProofSize(MinHeight), 16576},
		{"ProofSize(MaxHeight)", ProofSize(MaxHeight), 16896},
	} {
		if tc.got != tc.want {
			t.Errorf("%s = %d, want %d", tc.name, tc.got, tc.want)
		}
	}
}

// TestHashes pins down which functions the two names stand for. Keccak256 is
// the original Keccak with its 0x01 padding, not the SHA3-256 of FIPS 202,
// whose digest of the empty string starts with a7ffc6f8.
func TestHashes(t *testing.T) {
	for _, tc := range []struct {
		h     Hash
		name  string
		empty string
		abc   string
	}{
		{
			SHA256, "sha256",
			"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
			"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
		},
		{
			Keccak256, "keccak256",
			"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470",
			"4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45",
		},
	} {
		if !tc.h.Valid() {
			t.Errorf("%s is not valid", tc.name)
		}
		if tc.h.String() != tc.name {
			t.Errorf("String() = %q, want %q", tc.h.String(), tc.name)
		}
		empty := tc.h.Sum(nil)
		if got := hex.EncodeToString(empty[:]); got != tc.empty {
			t.Errorf("%s of nothing = %s", tc.name, got)
		}
		abc := tc.h.Sum([]byte("abc"))
		if got := hex.EncodeToString(abc[:]); got != tc.abc {
			t.Errorf("%s of abc = %s", tc.name, got)
		}
	}

	for _, h := range []Hash{0, 3, 255} {
		if h.Valid() {
			t.Errorf("hash %d is valid", h)
		}
		if h.String() != "unknown" {
			t.Errorf("hash %d is called %q", h, h.String())
		}
	}
}

func TestVerify(t *testing.T) {
	msg := []byte("bind this key to my account")
	for _, h := range bothHashes {
		for _, tc := range []struct {
			height int
			leaves []int
		}{
			{6, []int{0, 1, 2, 31, 32, 37, 62, 63}},
			{7, []int{0, 64, 127}},
			{11, []int{1365, 682, 2047}},
			{16, []int{0, 21845, 43690, 65535}},
		} {
			keys := map[int]testKey{}
			for _, leaf := range tc.leaves {
				keys[leaf] = testKey{h, byte(leaf)}
			}
			tree := newTestTree(h, tc.height, keys)
			for _, leaf := range tc.leaves {
				proof := append(keys[leaf].sign(msg), tree.path(leaf)...)
				if len(proof) != ProofSize(tc.height) {
					t.Fatalf("%s, height %d: proof of %d bytes", h, tc.height, len(proof))
				}
				if err := Verify(h, tree.root(), tc.height, leaf, msg, proof); err != nil {
					t.Errorf("%s, height %d, leaf %d: %v", h, tc.height, leaf, err)
				}
			}
		}
	}
}

// TestVerifyMessages signs messages of very different sizes: the empty one,
// single bytes and a long one.
func TestVerifyMessages(t *testing.T) {
	long := make([]byte, 70000)
	for i := range long {
		long[i] = byte(i * 7)
	}
	for _, h := range bothHashes {
		for i, msg := range [][]byte{nil, {0}, {0xff}, []byte("a"), []byte("b"), long} {
			root, proof := testProof(h, MinHeight, 5+i, msg)
			if err := Verify(h, root, MinHeight, 5+i, msg, proof); err != nil {
				t.Errorf("%s, message %d: %v", h, i, err)
			}
		}
	}
}

func TestVerifyRejectsChangedProof(t *testing.T) {
	const height, leaf = MinHeight, 37
	msg := []byte("bind this key to my account")
	for _, h := range bothHashes {
		root, proof := testProof(h, height, leaf, msg)
		if err := Verify(h, root, height, leaf, msg, proof); err != nil {
			t.Fatalf("%s: %v", h, err)
		}

		// One flipped bit anywhere breaks the proof: in a secret, in the hash
		// of a secret that stays private, in a sibling of the path.
		positions := []int{
			0, 31, 32, 63, 64, // first pair and the start of the second
			SignatureSize - 64, SignatureSize - 33, SignatureSize - 32, SignatureSize - 1,
			SignatureSize, SignatureSize + 31, SignatureSize + 32, // path
			len(proof) - 32, len(proof) - 1,
		}
		for at := 101; at < len(proof); at += 211 {
			positions = append(positions, at)
		}
		for _, at := range positions {
			for _, mask := range []byte{0x01, 0x80} {
				changed := append([]byte(nil), proof...)
				changed[at] ^= mask
				if err := Verify(h, root, height, leaf, msg, changed); err != ErrMismatch {
					t.Fatalf("%s: byte %d changed, got %v", h, at, err)
				}
			}
		}

		// Two pairs swapped, two siblings swapped.
		swapped := append([]byte(nil), proof...)
		copy(swapped[0:64], proof[64:128])
		copy(swapped[64:128], proof[0:64])
		if err := Verify(h, root, height, leaf, msg, swapped); err != ErrMismatch {
			t.Errorf("%s: pairs swapped, got %v", h, err)
		}
		swapped = append([]byte(nil), proof...)
		copy(swapped[SignatureSize:SignatureSize+32], proof[SignatureSize+32:SignatureSize+64])
		copy(swapped[SignatureSize+32:SignatureSize+64], proof[SignatureSize:SignatureSize+32])
		if err := Verify(h, root, height, leaf, msg, swapped); err != ErrMismatch {
			t.Errorf("%s: siblings swapped, got %v", h, err)
		}

		// The halves of a pair swapped: a hash shown where the secret goes.
		swapped = append([]byte(nil), proof...)
		copy(swapped[0:32], proof[32:64])
		copy(swapped[32:64], proof[0:32])
		if err := Verify(h, root, height, leaf, msg, swapped); err != ErrMismatch {
			t.Errorf("%s: halves of a pair swapped, got %v", h, err)
		}

		// The public key itself is not a signature of anything.
		key := testKey{h, byte(leaf)}
		tree := newTestTree(h, height, map[int]testKey{leaf: key})
		forged := append(key.public(), tree.path(leaf)...)
		if err := Verify(h, root, height, leaf, msg, forged); err != ErrMismatch {
			t.Errorf("%s: public key shown as a signature, got %v", h, err)
		}
	}
}

func TestVerifyRejectsChangedRequest(t *testing.T) {
	const height, leaf = MinHeight, 37
	msg := []byte("bind this key to my account")
	for _, h := range bothHashes {
		root, proof := testProof(h, height, leaf, msg)

		// Another message, however close.
		for _, other := range [][]byte{
			nil,
			[]byte("bind this key to my accounu"),
			[]byte("bind this key to my account "),
			[]byte("bind this key to my accoun"),
			[]byte("Bind this key to my account"),
		} {
			if err := Verify(h, root, height, leaf, other, proof); err != ErrMismatch {
				t.Errorf("%s: message %q, got %v", h, other, err)
			}
		}

		// Another leaf: the path only leads to the root from where it started.
		for other := 0; other < Leaves(height); other++ {
			if other == leaf {
				continue
			}
			if err := Verify(h, root, height, other, msg, proof); err != ErrMismatch {
				t.Fatalf("%s: leaf %d, got %v", h, other, err)
			}
		}

		// Another root.
		for at := 0; at < HashSize; at++ {
			other := root
			other[at] ^= 0x10
			if err := Verify(h, other, height, leaf, msg, proof); err != ErrMismatch {
				t.Fatalf("%s: root byte %d changed, got %v", h, at, err)
			}
		}
		if err := Verify(h, [HashSize]byte{}, height, leaf, msg, proof); err != ErrMismatch {
			t.Errorf("%s: zero root, got %v", h, err)
		}

		// The other hash function.
		other := SHA256
		if h == SHA256 {
			other = Keccak256
		}
		if err := Verify(other, root, height, leaf, msg, proof); err != ErrMismatch {
			t.Errorf("%s proof checked with %s, got %v", h, other, err)
		}
	}
}

func TestVerifyRejectsBadArguments(t *testing.T) {
	const height, leaf = MinHeight, 37
	msg := []byte("bind this key to my account")
	root, proof := testProof(SHA256, height, leaf, msg)

	for _, tc := range []struct {
		name   string
		h      Hash
		height int
		leaf   int
		proof  []byte
		want   error
	}{
		{"valid", SHA256, height, leaf, proof, nil},
		{"hash 0", 0, height, leaf, proof, ErrUnknownHash},
		{"hash 3", 3, height, leaf, proof, ErrUnknownHash},
		{"height 0", SHA256, 0, 0, proof, ErrHeight},
		{"height 5", SHA256, MinHeight - 1, leaf % 32, proof[:ProofSize(MinHeight-1)], ErrHeight},
		{"height 17", SHA256, MaxHeight + 1, leaf, make([]byte, ProofSize(MaxHeight+1)), ErrHeight},
		{"height -1", SHA256, -1, leaf, proof, ErrHeight},
		{"leaf -1", SHA256, height, -1, proof, ErrLeafIndex},
		{"leaf 64", SHA256, height, 64, proof, ErrLeafIndex},
		{"leaf 64+37", SHA256, height, 64 + leaf, proof, ErrLeafIndex},
		{"no proof", SHA256, height, leaf, nil, ErrProofSize},
		{"proof one byte short", SHA256, height, leaf, proof[:len(proof)-1], ErrProofSize},
		{"proof one byte long", SHA256, height, leaf, append(append([]byte(nil), proof...), 0), ErrProofSize},
		{"proof one sibling short", SHA256, height, leaf, proof[:len(proof)-HashSize], ErrProofSize},
		{"signature alone", SHA256, height, leaf, proof[:SignatureSize], ErrProofSize},
		// A proof cannot pass for one of a taller or shorter tree.
		{"height 7, proof of 6", SHA256, height + 1, leaf, proof, ErrProofSize},
		{"height 7, padded proof", SHA256, height + 1, leaf, append(append([]byte(nil), proof...), make([]byte, HashSize)...), ErrMismatch},
	} {
		if err := Verify(tc.h, root, tc.height, tc.leaf, msg, tc.proof); err != tc.want {
			t.Errorf("%s: got %v, want %v", tc.name, err, tc.want)
		}
	}
}

// TestSHA256TreeIsTheChainTree checks the SHA-256 tree against crypto/merkle,
// the native implementation of the Merkle tree gno.land itself uses for its
// blocks: same leaf and node hashing, same root, same proof layout.
func TestSHA256TreeIsTheChainTree(t *testing.T) {
	msg := []byte("bind this key to my account")
	for _, tc := range []struct {
		height int
		leaves []int
	}{
		{6, []int{0, 41, 63}},
		{9, []int{1, 170, 341, 511}},
	} {
		keys := map[int]testKey{}
		for _, leaf := range tc.leaves {
			keys[leaf] = testKey{SHA256, byte(leaf)}
		}
		tree := newTestTree(SHA256, tc.height, keys)
		root := tree.root()

		// The root, computed by crypto/merkle from what the leaves stand for.
		count := len(tree.items)
		encoded := []byte{byte(count >> 24), byte(count >> 16), byte(count >> 8), byte(count)}
		for _, item := range tree.items {
			size := len(item)
			encoded = append(encoded, byte(size>>24), byte(size>>16), byte(size>>8), byte(size))
			encoded = append(encoded, item...)
		}
		if got := merkle.HashFromByteSlices(encoded); hex.EncodeToString(got) != hex.EncodeToString(root[:]) {
			t.Fatalf("height %d: crypto/merkle root %x, tree root %x", tc.height, got, root)
		}

		// The path part of a proof is a crypto/merkle proof of the public key.
		for _, leaf := range tc.leaves {
			path := tree.path(leaf)
			if !merkle.VerifySimpleProof(root[:], keys[leaf].public(), leaf, count, path) {
				t.Errorf("height %d, leaf %d: crypto/merkle rejects the path", tc.height, leaf)
			}
			proof := append(keys[leaf].sign(msg), path...)
			if err := Verify(SHA256, root, tc.height, leaf, msg, proof); err != nil {
				t.Errorf("height %d, leaf %d: %v", tc.height, leaf, err)
			}
		}
	}
}