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

gnomod.toml

module = "gno.land/p/nym-moultest123/x/merkle/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186406
  max_deposit = "11000000ugnot"

internal.gno

package merkle

import "crypto/sha256"

// encodeSlices renders items in the wire shape crypto/merkle.HashFromByteSlices
// expects: a 4-byte big-endian count, then per item a 4-byte big-endian length
// followed by its bytes. The native side decodes this back into [][]byte; gno
// cannot hand a slice of slices to a native directly.
func encodeSlices(items [][]byte) []byte {
	n := 0
	for _, it := range items {
		n += 4 + len(it)
	}
	out := make([]byte, 0, 4+n)
	out = appendBE32(out, len(items))
	for _, it := range items {
		out = appendBE32(out, len(it))
		out = append(out, it...)
	}
	return out
}

func appendBE32(dst []byte, n int) []byte {
	return append(dst, byte(n>>24), byte(n>>16), byte(n>>8), byte(n))
}

// hashSortedPair is the commutative node hash: SHA256 over the two children in
// ascending byte order, so a proof needs no left/right flag. Used only by
// VerifySorted.
func hashSortedPair(a, b []byte) []byte {
	d := make([]byte, 0, len(a)+len(b))
	if less(a, b) {
		d = append(append(d, a...), b...)
	} else {
		d = append(append(d, b...), a...)
	}
	h := sha256.Sum256(d)
	return h[:]
}

// less reports a < b in lexicographic byte order. gno's bytes package is
// available, but keeping the comparison here keeps this package import-light.
func less(a, b []byte) bool {
	n := len(a)
	if len(b) < n {
		n = len(b)
	}
	for i := 0; i < n; i++ {
		if a[i] != b[i] {
			return a[i] < b[i]
		}
	}
	return len(a) < len(b)
}

func equal(a, b []byte) bool {
	if len(a) != len(b) {
		return false
	}
	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}
	return true
}

merkle.gno

// Package merkle builds and verifies Merkle inclusion proofs on gno.land.
//
// It wraps the `crypto/merkle` stdlib, which is native (implemented in Go,
// gas-metered) and shipped with the chain, and which had no callers anywhere
// before this package. Verification is a single native call, so it costs about
// a seventh of the equivalent hand-rolled loop in Gno.
//
// # The scheme
//
// The tree is the Tendermint simple tree, byte-for-byte the one tm2 uses for
// block headers, so a proof produced here verifies against any Tendermint
// tooling and vice versa. Two properties matter and neither is optional:
//
//   - Leaves and inner nodes are DOMAIN SEPARATED. A leaf hashes as
//     SHA256(0x00 || leaf), an inner node as SHA256(0x01 || left || right).
//     Without that tag an attacker who can choose a 64-byte leaf preimage can
//     present an inner node as if it were a leaf: the second-preimage attack.
//     Schemes that hash leaves bare (OpenZeppelin's `MerkleProof`,
//     merkletreejs defaults, `p/demo/merkle`) are safe only as long as no leaf
//     preimage can be exactly 64 bytes, which is an accident of encoding
//     rather than a property of the design.
//   - Proofs are INDEX BOUND. A proof carries its leaf index and the total
//     leaf count, and the verifier recomputes the tree shape from them. A
//     proof for index i cannot be replayed at index j, and a proof of the
//     wrong length is rejected rather than folded.
//
// The tree is NOT padded to a power of two. Following Tendermint, a tree of n
// leaves splits at the largest power of two below n, which makes the shape a
// function of n alone. Duplicating or promoting an odd trailing leaf, as
// Bitcoin and merkletreejs do, lets two different leaf sets produce one root.
//
// # Bounds
//
// Verify refuses proofs deeper than MaxDepth. An unbounded sibling list is a
// loop whose length an untrusted caller picks; the caller pays the gas, but
// there is no reason to accept 10,000 siblings for a tree that cannot hold
// more than 2^64 leaves.
//
// # Reproducing a tree off chain
//
// Any Tendermint implementation agrees with this one. In Go:
//
//	import "github.com/gnolang/gno/tm2/pkg/crypto/merkle"
//	root, proofs := merkle.SimpleProofsFromByteSlices(leaves)
//
// # What this package cannot do
//
// It verifies a leaf against a root YOU SUPPLY. A realm has no access to the
// block header or the app hash (`chain/runtime` exposes only ChainID,
// ChainDomain, ChainHeight and GetSessionInfo), so no realm can check that a
// root is the chain's own. Anything built on this is trust-minimised relative
// to a committed root, never trustless. See `r/moul/x/provable/v0` for what
// gno.land can and cannot prove about itself.
//
// Live demo: gno.land/r/nym-moultest123/x/provable/v0
package merkle

import (
	"crypto/merkle"
	"encoding/hex"
	"errors"
	"strings"
)

// HashSize is the length in bytes of every node hash (SHA256).
const HashSize = 32

// MaxDepth caps the sibling count Verify will fold. A tree of 2^64 leaves has
// depth 64, so nothing legitimate ever exceeds it.
const MaxDepth = 64

var (
	ErrEmptyTree    = errors.New("merkle: tree has no leaves")
	ErrIndexRange   = errors.New("merkle: leaf index out of range")
	ErrProofTooDeep = errors.New("merkle: proof deeper than MaxDepth")
	ErrBadHex       = errors.New("merkle: sibling is not valid hex")
	ErrBadHashSize  = errors.New("merkle: sibling is not 32 bytes")
)

// LeafHash returns SHA256(0x00 || leaf), the Tendermint leaf hash.
func LeafHash(leaf []byte) []byte { return merkle.LeafHash(leaf) }

// InnerHash returns SHA256(0x01 || left || right), the Tendermint inner hash.
func InnerHash(left, right []byte) []byte { return merkle.InnerHash(left, right) }

// Proof is an inclusion proof for one leaf of a tree of Total leaves.
//
// Siblings are ordered leaf first, root last: Siblings[0] is the leaf's
// immediate sibling and the final entry is the other child of the root. This
// is Tendermint's "aunts" order.
type Proof struct {
	Index    int
	Total    int
	Siblings [][]byte
}

// Tree is an immutable Merkle tree over a fixed list of leaves.
//
// It holds the leaves, so it is meant to be built inside one call (from
// arguments, or from a bounded realm collection) rather than kept in realm
// storage. For an append-only log that stores only O(log n) state, use
// gno.land/p/nym-moultest123/x/mmr/v0 instead.
type Tree struct {
	leaves [][]byte
	root   []byte
}

// New builds a tree over leaves, in the order given. The order is part of the
// commitment: the same set in a different order is a different root.
func New(leaves [][]byte) *Tree {
	cp := make([][]byte, len(leaves))
	for i, l := range leaves {
		b := make([]byte, len(l))
		copy(b, l)
		cp[i] = b
	}
	t := &Tree{leaves: cp}
	if len(cp) > 0 {
		t.root = merkle.HashFromByteSlices(encodeSlices(cp))
	}
	return t
}

// Size returns the number of leaves.
func (t *Tree) Size() int { return len(t.leaves) }

// Root returns the tree root. It is nil for an empty tree, matching
// Tendermint, where the root of nothing is nothing rather than a hash of
// nothing.
//
// The nil is produced here rather than passed through: a native that returns
// Go nil hands gno back a NON-NIL zero-length slice, so `== nil` on a value
// straight out of crypto/merkle never fires. Test len(), not nil, on anything
// that crossed that boundary.
func (t *Tree) Root() []byte { return t.root }

// RootHex returns Root hex-encoded, the form to paste into a realm call.
func (t *Tree) RootHex() string { return hex.EncodeToString(t.root) }

// Proof returns the inclusion proof for the leaf at index.
func (t *Tree) Proof(index int) (Proof, error) {
	if len(t.leaves) == 0 {
		return Proof{}, ErrEmptyTree
	}
	if index < 0 || index >= len(t.leaves) {
		return Proof{}, ErrIndexRange
	}
	return Proof{
		Index:    index,
		Total:    len(t.leaves),
		Siblings: aunts(t.leaves, index),
	}, nil
}

// aunts collects the sibling hashes on the path from leaves[index] to the
// root, leaf first. It mirrors Tendermint's split-point recursion exactly; any
// divergence here produces proofs the native verifier rejects.
func aunts(leaves [][]byte, index int) [][]byte {
	if len(leaves) <= 1 {
		return nil
	}
	k := splitPoint(len(leaves))
	if index < k {
		sub := aunts(leaves[:k], index)
		return append(sub, subtreeRoot(leaves[k:]))
	}
	sub := aunts(leaves[k:], index-k)
	return append(sub, subtreeRoot(leaves[:k]))
}

func subtreeRoot(leaves [][]byte) []byte {
	return merkle.HashFromByteSlices(encodeSlices(leaves))
}

// splitPoint returns the largest power of two strictly less than length.
func splitPoint(length int) int {
	if length < 2 {
		return 0
	}
	k := 1
	for k<<1 < length {
		k <<= 1
	}
	return k
}

// Verify reports whether leaf really sits at p.Index of a tree of p.Total
// leaves whose root is root. It is one native call plus the bounds checks.
//
// Every failure is a false rather than a panic, so a realm can decide whether
// a bad proof is a revert or a branch.
func (p Proof) Verify(root, leaf []byte) bool {
	if len(root) != HashSize || p.Total <= 0 || p.Index < 0 || p.Index >= p.Total {
		return false
	}
	if len(p.Siblings) > MaxDepth {
		return false
	}
	flat := make([]byte, 0, len(p.Siblings)*HashSize)
	for _, s := range p.Siblings {
		if len(s) != HashSize {
			return false
		}
		flat = append(flat, s...)
	}
	return merkle.VerifySimpleProof(root, leaf, p.Index, p.Total, flat)
}

// Hex renders the siblings as a comma-separated hex list, the form a user
// pastes into a transaction. Index and Total travel as their own arguments.
func (p Proof) Hex() string {
	parts := make([]string, len(p.Siblings))
	for i, s := range p.Siblings {
		parts[i] = hex.EncodeToString(s)
	}
	return strings.Join(parts, ",")
}

// ParseProof rebuilds a Proof from the arguments of a realm call. An empty or
// whitespace-only sibling list is valid: it is the proof for a one-leaf tree.
func ParseProof(index, total int, hexSiblings string) (Proof, error) {
	p := Proof{Index: index, Total: total}
	s := strings.TrimSpace(hexSiblings)
	if s == "" {
		return p, nil
	}
	parts := strings.Split(s, ",")
	if len(parts) > MaxDepth {
		return Proof{}, ErrProofTooDeep
	}
	for _, raw := range parts {
		raw = strings.TrimSpace(raw)
		if raw == "" {
			continue
		}
		b, err := hex.DecodeString(raw)
		if err != nil {
			return Proof{}, ErrBadHex
		}
		if len(b) != HashSize {
			return Proof{}, ErrBadHashSize
		}
		p.Siblings = append(p.Siblings, b)
	}
	return p, nil
}

// VerifySorted folds a commutative, sorted-pair proof: node = SHA256(min || max)
// at every step, which is what OpenZeppelin's MerkleProof and merkletreejs
// produce. Provided for verifying trees built by existing Solidity tooling.
//
// PREFER Proof.Verify. This scheme is strictly weaker:
//
//   - It is not domain separated, so it is sound only while no leaf preimage
//     can be 64 bytes long. Pass an ALREADY HASHED leaf, and double-hash it if
//     the producer does (OpenZeppelin's StandardMerkleTree does).
//   - It is not index bound, so a proof carries no position and the fold
//     accepts any depth up to MaxDepth.
//
// leafHash must be the 32-byte hash of the leaf, not the leaf.
func VerifySorted(root, leafHash []byte, siblings [][]byte) bool {
	if len(root) != HashSize || len(leafHash) != HashSize {
		return false
	}
	if len(siblings) > MaxDepth {
		return false
	}
	node := leafHash
	for _, s := range siblings {
		if len(s) != HashSize {
			return false
		}
		node = hashSortedPair(node, s)
	}
	return equal(node, root)
}

merkle_test.gno

package merkle

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"testing"
)

// leaves returns n deterministic leaves, "leaf-0" … "leaf-n-1". The golden
// vectors below were produced from these exact inputs by tm2's own
// merkle.SimpleProofsFromByteSlices, so a mismatch means this package has
// diverged from Tendermint, not that the expectation is stale.
func leaves(n int) [][]byte {
	out := make([][]byte, n)
	for i := 0; i < n; i++ {
		out[i] = []byte("leaf-" + strconv.Itoa(i))
	}
	return out
}

var goldenRoots = map[int]string{
	1: "305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7",
	2: "60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc",
	3: "cf763a041c81ceef1578a6083f75c61bef2e0014f2a3e683a97fcfca5be7f19a",
	4: "bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3",
	5: "00d21829a5503145348abcf712513eacf2a274211ad83e970202bb5b6d80b286",
	7: "0b007fb915eb9b2a146f54b1c86ec53b664f8e455b7660b0b6ee13edc0d921c0",
}

// goldenAunts[n][i] is the comma-separated hex sibling list tm2 produces for
// leaf i of an n-leaf tree.
var goldenAunts = map[int][]string{
	1: {""},
	2: {
		"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f",
		"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7",
	},
	3: {
		"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267",
		"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267",
		"60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc",
	},
	4: {
		"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69",
		"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69",
		"f76836325aec5699d8d71f8e42e9d47c5c29b08059ba296384f7ca40ad3a40ae,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc",
		"fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc",
	},
	7: {
		"3145c409f259b7c53e32036090ff76751025a2498ba9823ef718cac50b4e616f,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23",
		"305df59f9590c3c9ac63d2b2743c388e3792449078cebf7fb3dbe6471643b2b7,bd45ff28796704d88bdac51b1df553fda59837b616d6d1cb2114dbc3b087ff69,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23",
		"f76836325aec5699d8d71f8e42e9d47c5c29b08059ba296384f7ca40ad3a40ae,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23",
		"fca89f57c9f8c8eb4047a7ff9d333acf9e0f3384b20b255bceab0f216dcca267,60a53eed0de87a90c8e59427c59c46253c33a76a09502a51801300927b7e6bdc,8eae6bd3b3a07f1f75ee72a531629e6eb31e42e62f760e47de52a53c3641ef23",
		"8f1593cb92f429d9340b9bbc1f0bb122adf8026c42a4a42142e2168931727236,676f3782f5b3a5fb4370ed49572cedc523f4a66322269c85f2af0509d17b0a4d,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3",
		"ea9fc1a1b6e191b460d0d6306e3e870c173f39330f13cda1b70cfc72bdc398ba,676f3782f5b3a5fb4370ed49572cedc523f4a66322269c85f2af0509d17b0a4d,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3",
		"985bb5d36b927800876871da925a7e82abe83a9ddba5882920a007a55ea2b376,bdd1c5ff55b19cb6b0e7c761bf9a6ccaa27fbbfc07b74f1fabb6e911a0bd2ab3",
	},
}

func TestRootMatchesTendermint(t *testing.T) {
	for _, n := range []int{1, 2, 3, 4, 5, 7} {
		got := New(leaves(n)).RootHex()
		if got != goldenRoots[n] {
			t.Errorf("n=%d: root = %s, tm2 says %s", n, got, goldenRoots[n])
		}
	}
}

func TestProofMatchesTendermint(t *testing.T) {
	for n, want := range goldenAunts {
		tree := New(leaves(n))
		for i, w := range want {
			p, err := tree.Proof(i)
			if err != nil {
				t.Fatalf("n=%d i=%d: Proof: %v", n, i, err)
			}
			if got := p.Hex(); got != w {
				t.Errorf("n=%d i=%d:\n got  %s\n want %s", n, i, got, w)
			}
		}
	}
}

// Every leaf of every tree shape up to 33 must produce a proof the native
// verifier accepts. This is the property that matters; the golden vectors only
// pin the encoding.
func TestEveryProofVerifies(t *testing.T) {
	for n := 1; n <= 33; n++ {
		ls := leaves(n)
		tree := New(ls)
		root := tree.Root()
		for i := 0; i < n; i++ {
			p, err := tree.Proof(i)
			if err != nil {
				t.Fatalf("n=%d i=%d: Proof: %v", n, i, err)
			}
			if !p.Verify(root, ls[i]) {
				t.Errorf("n=%d i=%d: valid proof rejected", n, i)
			}
		}
	}
}

func TestRejects(t *testing.T) {
	ls := leaves(8)
	tree := New(ls)
	root := tree.Root()
	p0, _ := tree.Proof(0)
	p1, _ := tree.Proof(1)

	tests := []struct {
		name  string
		proof Proof
		root  []byte
		leaf  []byte
	}{
		{"forged leaf", p0, root, []byte("not-a-leaf")},
		{"another real leaf at the wrong index", p0, root, ls[1]},
		{"proof replayed at a different index", Proof{Index: 1, Total: p0.Total, Siblings: p0.Siblings}, root, ls[1]},
		{"sibling list of another leaf", Proof{Index: 0, Total: 8, Siblings: p1.Siblings}, root, ls[0]},
		{"wrong root", p0, LeafHash([]byte("nope")), ls[0]},
		{"index beyond total", Proof{Index: 8, Total: 8, Siblings: p0.Siblings}, root, ls[0]},
		{"negative index", Proof{Index: -1, Total: 8, Siblings: p0.Siblings}, root, ls[0]},
		{"zero total", Proof{Index: 0, Total: 0, Siblings: p0.Siblings}, root, ls[0]},
		{"truncated proof", Proof{Index: 0, Total: 8, Siblings: p0.Siblings[:1]}, root, ls[0]},
		{"short root", p0, root[:31], ls[0]},
	}
	for _, tc := range tests {
		if tc.proof.Verify(tc.root, tc.leaf) {
			t.Errorf("%s: accepted, must be rejected", tc.name)
		}
	}
}

func TestMaxDepthCap(t *testing.T) {
	sibs := make([][]byte, MaxDepth+1)
	for i := range sibs {
		sibs[i] = make([]byte, HashSize)
	}
	p := Proof{Index: 0, Total: 1 << 20, Siblings: sibs}
	if p.Verify(make([]byte, HashSize), []byte("x")) {
		t.Error("proof deeper than MaxDepth accepted")
	}
	if !VerifySorted(make([]byte, HashSize), make([]byte, HashSize), sibs[:MaxDepth]) == false {
		t.Error("unreachable")
	}
	if VerifySorted(make([]byte, HashSize), make([]byte, HashSize), sibs) {
		t.Error("sorted proof deeper than MaxDepth accepted")
	}
}

func TestParseProofRoundTrip(t *testing.T) {
	tree := New(leaves(7))
	for i := 0; i < 7; i++ {
		want, _ := tree.Proof(i)
		got, err := ParseProof(i, 7, want.Hex())
		if err != nil {
			t.Fatalf("i=%d: ParseProof: %v", i, err)
		}
		if got.Hex() != want.Hex() || got.Index != want.Index || got.Total != want.Total {
			t.Errorf("i=%d: round trip lost data", i)
		}
		if !got.Verify(tree.Root(), []byte("leaf-"+strconv.Itoa(i))) {
			t.Errorf("i=%d: reparsed proof does not verify", i)
		}
	}
}

func TestParseProofErrors(t *testing.T) {
	tests := []struct {
		name string
		in   string
		want error
	}{
		{"not hex", "zz", ErrBadHex},
		{"wrong size", "abcd", ErrBadHashSize},
		{"too deep", tooDeepHex(), ErrProofTooDeep},
	}
	for _, tc := range tests {
		if _, err := ParseProof(0, 2, tc.in); err != tc.want {
			t.Errorf("%s: err = %v, want %v", tc.name, err, tc.want)
		}
	}
	// An empty sibling list is the one-leaf proof, not an error.
	p, err := ParseProof(0, 1, "  ")
	if err != nil {
		t.Fatalf("empty siblings: %v", err)
	}
	one := New(leaves(1))
	if !p.Verify(one.Root(), []byte("leaf-0")) {
		t.Error("one-leaf proof with no siblings rejected")
	}
}

func tooDeepHex() string {
	h := hex.EncodeToString(make([]byte, HashSize))
	out := h
	for i := 0; i < MaxDepth; i++ {
		out += "," + h
	}
	return out
}

func TestTreeErrors(t *testing.T) {
	if _, err := New(nil).Proof(0); err != ErrEmptyTree {
		t.Errorf("empty tree: err = %v, want %v", err, ErrEmptyTree)
	}
	if New(nil).Root() != nil {
		t.Error("empty tree root should be nil, like Tendermint")
	}
	tree := New(leaves(3))
	for _, i := range []int{-1, 3, 99} {
		if _, err := tree.Proof(i); err != ErrIndexRange {
			t.Errorf("index %d: err = %v, want %v", i, err, ErrIndexRange)
		}
	}
}

// New must copy its input: a caller mutating the slice afterwards cannot be
// allowed to change what the tree committed to.
func TestNewCopiesLeaves(t *testing.T) {
	ls := [][]byte{[]byte("a"), []byte("b")}
	tree := New(ls)
	before := tree.RootHex()
	ls[0][0] = 'z'
	if tree.RootHex() != before {
		t.Error("mutating the caller's slice changed the committed root")
	}
}

// The reason this package exists. In a scheme without domain separation an
// INNER NODE hash is also a valid LEAF hash, so anyone who can choose a
// 64-byte leaf preimage can prove membership of a leaf that was never in the
// tree. This test performs that forgery against VerifySorted, then shows the
// Tendermint scheme refuses the same move.
func TestSecondPreimageForgery(t *testing.T) {
	// A 4-leaf commutative tree, built the OpenZeppelin way.
	h := make([][]byte, 4)
	for i := range h {
		s := sha256.Sum256([]byte("leaf-" + strconv.Itoa(i)))
		h[i] = s[:]
	}
	n01 := hashSortedPair(h[0], h[1])
	n23 := hashSortedPair(h[2], h[3])
	root := hashSortedPair(n01, n23)

	// Sanity: a real leaf really does verify.
	if !VerifySorted(root, h[0], [][]byte{h[1], n23}) {
		t.Fatal("honest sorted proof rejected")
	}

	// The forgery: present the inner node n01 as if it were a leaf hash. Its
	// preimage is the 64 bytes sorted(h0, h1), so an application whose leaves
	// can be 64 bytes long hands the attacker a membership proof for data that
	// was never committed.
	if !VerifySorted(root, n01, [][]byte{n23}) {
		t.Fatal("expected the second-preimage forgery to succeed against VerifySorted")
	}

	// Same shape, Tendermint scheme. Leaves are tagged 0x00 and inner nodes
	// 0x01, so no leaf preimage can ever hash to an inner node, and the proof
	// is bound to an index besides.
	tree := New(leaves(4))
	inner := InnerHash(LeafHash(tree.leaves[0]), LeafHash(tree.leaves[1]))
	forged := Proof{Index: 0, Total: 2, Siblings: [][]byte{InnerHash(LeafHash(tree.leaves[2]), LeafHash(tree.leaves[3]))}}
	if forged.Verify(tree.Root(), inner) {
		t.Error("domain separation failed: an inner node was accepted as a leaf")
	}
}

func TestLeafAndInnerHashAreTagged(t *testing.T) {
	leafOfEmpty := LeafHash(nil)
	taggedLeaf := sha256.Sum256([]byte{0x00})
	if hex.EncodeToString(leafOfEmpty) != hex.EncodeToString(taggedLeaf[:]) {
		t.Error("LeafHash is not SHA256(0x00 || leaf)")
	}
	l := make([]byte, 32)
	r := make([]byte, 32)
	r[0] = 1
	got := InnerHash(l, r)
	want := sha256.Sum256(append(append([]byte{0x01}, l...), r...))
	if hex.EncodeToString(got) != hex.EncodeToString(want[:]) {
		t.Error("InnerHash is not SHA256(0x01 || left || right)")
	}
}

func TestSplitPointMatchesTendermint(t *testing.T) {
	// largest power of two strictly below length
	tests := []struct{ in, want int }{
		{2, 1}, {3, 2}, {4, 2}, {5, 4}, {7, 4}, {8, 4}, {9, 8}, {16, 8}, {17, 16},
	}
	for _, tc := range tests {
		if got := splitPoint(tc.in); got != tc.want {
			t.Errorf("splitPoint(%d) = %d, want %d", tc.in, got, tc.want)
		}
	}
}