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/mmr/v0"
gno = "0.9"

[addpkg]
  creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv"
  height = 186409
  max_deposit = "10000000ugnot"

mmr.gno

// Package mmr implements a Merkle Mountain Range: an append-only log with a
// root that updates in O(log n) and inclusion proofs of O(log n) size.
//
// # Why not a plain Merkle tree
//
// gno.land/p/nym-moultest123/x/merkle/v0 commits to a FIXED list. Adding a leaf means
// rebuilding from every leaf, which on chain means re-reading the whole set
// and re-hashing it, every time. An MMR never rebuilds: an append hashes at
// most log2(n) times and touches nothing else.
//
// That is the shape any on-chain log wants. A wiki committing to its revision
// history, a forge committing to its objects, an agent realm committing to the
// receipts it issued: all append, none rewrite.
//
// # The structure
//
// An MMR is a list of perfect binary trees ("mountains") of strictly
// decreasing height, one per set bit of the leaf count. Eleven leaves is
// 8 + 2 + 1, so three mountains of height 3, 1 and 0. Appending a leaf pushes
// a height-0 mountain and merges equal-height neighbours, exactly like
// incrementing a binary counter.
//
// The root is the peaks "bagged" right to left:
//
//	root = InnerHash(p0, InnerHash(p1, InnerHash(p2, …)))
//
// Hashing is gno.land/p/nym-moultest123/x/merkle/v0's, which is Tendermint's: leaves are
// tagged 0x00 and inner nodes 0x01. Leaf and inner preimages therefore cannot
// collide, so the second-preimage forgery that works against untagged schemes
// does not apply here. See that package for the worked attack.
//
// # This IS the Tendermint tree
//
// The root above equals the Tendermint simple-tree root over the same leaves,
// at every size and not merely at powers of two. Tendermint splits an n-leaf
// tree at the largest power of two below n: that left half is exactly the
// first mountain, and the right half recurses through the remaining set bits,
// which is exactly the bagging. The two constructions coincide.
//
// So this package is a drop-in INCREMENTAL BUILDER for Tendermint roots.
// Append in O(log n) on chain and hand out a root that any Tendermint verifier
// accepts; proofs cross over in both directions, which
// TestMerkleProofVerifiesAgainstMMRRoot pins. Use merkle.New when the leaf set
// is fixed and you want the simpler proof encoding, use this when the log
// grows.
//
// # Proofs are bound to position and to size
//
// A Proof carries the leaf index and the leaf count the MMR had when it was
// issued. The verifier recomputes the whole peak structure from that count,
// which fixes the number of peaks, which mountain holds the leaf, the local
// index inside it, and therefore the exact expected length of every component
// of the proof. A proof cannot be replayed at another index, against another
// size, or padded.
//
// Because the root changes on every append, a proof is valid against the root
// at its own Total and no other. A realm that wants old proofs to keep
// verifying must keep the historical roots; Roots grow by one 32-byte hash per
// append, which is the price of an auditable log.
//
// # Storage
//
// Append stores one node per leaf plus one per merge, so 2n-popcount(n) hashes
// for n leaves, under 64 bytes per leaf amortised. That is what on-chain proof
// generation costs. A realm that only ever needs to VERIFY proofs, with the
// tree living off chain, should store the root alone and use
// gno.land/p/nym-moultest123/x/merkle/v0's Verify instead.
//
// Live demo: gno.land/r/nym-moultest123/x/provable/v0
package mmr

import (
	"encoding/hex"
	"errors"

	"gno.land/p/nym-moultest123/x/merkle/v0"
)

// HashSize is the length in bytes of every node hash.
const HashSize = merkle.HashSize

// MaxPeaks caps the peak count a Proof may claim. A 64-peak MMR would hold
// more than 2^64 leaves.
const MaxPeaks = 64

var (
	ErrEmpty      = errors.New("mmr: log is empty")
	ErrIndexRange = errors.New("mmr: leaf index out of range")
	ErrBadHex     = errors.New("mmr: hash is not valid hex")
	ErrBadSize    = errors.New("mmr: hash is not 32 bytes")
	ErrTooManyPeaks = errors.New("mmr: more peaks than MaxPeaks")
)

// peak is one mountain: the position of its root in nodes, and its height.
type peak struct {
	pos    int
	height int
}

// MMR is an append-only Merkle mountain range.
//
// The zero value is an empty, ready-to-use log.
type MMR struct {
	nodes  [][]byte // every node, in postorder: [left subtree][right subtree][root]
	peaks  []peak
	leaves int
}

// New returns an empty MMR.
func New() *MMR { return &MMR{} }

// Size returns the number of leaves appended so far.
func (m *MMR) Size() int { return m.leaves }

// Nodes returns the number of stored hashes, leaves and merges together. Use
// it to reason about storage growth.
func (m *MMR) Nodes() int { return len(m.nodes) }

// Append adds a leaf and returns its index. O(log n) hashes, no rebuild.
func (m *MMR) Append(leaf []byte) int {
	index := m.leaves
	m.nodes = append(m.nodes, merkle.LeafHash(leaf))
	m.peaks = append(m.peaks, peak{pos: len(m.nodes) - 1, height: 0})
	for len(m.peaks) >= 2 {
		right := m.peaks[len(m.peaks)-1]
		left := m.peaks[len(m.peaks)-2]
		if left.height != right.height {
			break
		}
		m.nodes = append(m.nodes, merkle.InnerHash(m.nodes[left.pos], m.nodes[right.pos]))
		m.peaks = m.peaks[:len(m.peaks)-2]
		m.peaks = append(m.peaks, peak{pos: len(m.nodes) - 1, height: left.height + 1})
	}
	m.leaves++
	return index
}

// Root returns the current root, nil while the log is empty.
func (m *MMR) Root() []byte {
	if len(m.peaks) == 0 {
		return nil
	}
	return bag(m.peakHashes())
}

// RootHex returns Root hex-encoded.
func (m *MMR) RootHex() string { return hex.EncodeToString(m.Root()) }

// PeakHashes returns the current peak hashes, left to right. This is the whole
// state a verifier needs, and it is O(log n).
func (m *MMR) PeakHashes() [][]byte { return m.peakHashes() }

func (m *MMR) peakHashes() [][]byte {
	out := make([][]byte, len(m.peaks))
	for i, p := range m.peaks {
		out[i] = m.nodes[p.pos]
	}
	return out
}

// bag folds peaks right to left: InnerHash(p0, InnerHash(p1, …)).
func bag(peaks [][]byte) []byte {
	if len(peaks) == 0 {
		return nil
	}
	acc := peaks[len(peaks)-1]
	for i := len(peaks) - 2; i >= 0; i-- {
		acc = merkle.InnerHash(peaks[i], acc)
	}
	return acc
}

// Proof is an inclusion proof for one leaf of a log that held Total leaves.
//
// Path holds the sibling hashes inside the leaf's own mountain, leaf first.
// Before and After hold the other peak hashes, in left-to-right order.
type Proof struct {
	Index  int
	Total  int
	Path   [][]byte
	Before [][]byte
	After  [][]byte
}

// Proof returns the inclusion proof for the leaf at index, against the current
// root.
func (m *MMR) Proof(index int) (Proof, error) {
	if m.leaves == 0 {
		return Proof{}, ErrEmpty
	}
	if index < 0 || index >= m.leaves {
		return Proof{}, ErrIndexRange
	}
	j, local := locate(m.leaves, index)
	hashes := m.peakHashes()
	return Proof{
		Index:  index,
		Total:  m.leaves,
		Path:   m.pathIn(m.peaks[j], local),
		Before: hashes[:j],
		After:  hashes[j+1:],
	}, nil
}

// pathIn walks down the perfect tree rooted at p, collecting the sibling at
// each level, and returns them leaf first.
//
// The layout is postorder, so for a node at position pos and height h the
// right child root sits at pos-1 and the left child root at pos-1-(2^h - 1),
// a perfect subtree of height h-1 holding 2^h - 1 nodes.
func (m *MMR) pathIn(p peak, local int) [][]byte {
	var out [][]byte
	pos, h := p.pos, p.height
	for h > 0 {
		rightRoot := pos - 1
		leftRoot := pos - 1 - ((1 << uint(h)) - 1)
		half := 1 << uint(h-1)
		if local < half {
			out = append([][]byte{m.nodes[rightRoot]}, out...)
			pos = leftRoot
		} else {
			out = append([][]byte{m.nodes[leftRoot]}, out...)
			pos = rightRoot
			local -= half
		}
		h--
	}
	return out
}

mmr_test.gno

package mmr

import (
	"strconv"
	"testing"

	"gno.land/p/nym-moultest123/x/merkle/v0"
)

func leafAt(i int) []byte { return []byte("entry-" + strconv.Itoa(i)) }

func build(n int) *MMR {
	m := New()
	for i := 0; i < n; i++ {
		if got := m.Append(leafAt(i)); got != i {
			panic("Append returned the wrong index")
		}
	}
	return m
}

// The property that matters: for every log size up to 40, every leaf ever
// appended has a proof that verifies against the root at that size.
func TestEveryProofVerifies(t *testing.T) {
	for n := 1; n <= 40; n++ {
		m := build(n)
		root := m.Root()
		for i := 0; i < n; i++ {
			p, err := m.Proof(i)
			if err != nil {
				t.Fatalf("n=%d i=%d: Proof: %v", n, i, err)
			}
			if !Verify(root, leafAt(i), p) {
				t.Errorf("n=%d i=%d: valid proof rejected", n, i)
			}
		}
	}
}

// A one-leaf MMR is a single height-0 mountain, so its root is just the
// tagged leaf hash and the proof is empty.
func TestSingleLeaf(t *testing.T) {
	m := build(1)
	if string(m.Root()) != string(merkle.LeafHash(leafAt(0))) {
		t.Error("one-leaf root is not the leaf hash")
	}
	p, err := m.Proof(0)
	if err != nil {
		t.Fatal(err)
	}
	if len(p.Path) != 0 || len(p.Before) != 0 || len(p.After) != 0 {
		t.Error("one-leaf proof should be empty")
	}
}

// The Tendermint simple tree and a right-bagged MMR are the SAME tree, at
// every size and not only at powers of two. Tendermint splits an n-leaf tree
// at the largest power of two below n: that left half is exactly the first
// mountain, and the right half recurses into the remaining set bits, which is
// exactly the bagging. So an MMR is a drop-in incremental builder for
// Tendermint roots: append in O(log n) on chain, hand out a root any
// Tendermint verifier accepts.
func TestRootMatchesTendermintTreeAtEverySize(t *testing.T) {
	for n := 1; n <= 40; n++ {
		ls := make([][]byte, n)
		for i := range ls {
			ls[i] = leafAt(i)
		}
		if got, want := build(n).RootHex(), merkle.New(ls).RootHex(); got != want {
			t.Errorf("n=%d: MMR root %s, Tendermint tree root %s", n, got, want)
		}
	}
}

// The consequence of the equality above: a proof produced by the fixed-list
// Tendermint tree verifies against the root an MMR maintained incrementally,
// and both packages agree leaf by leaf.
func TestMerkleProofVerifiesAgainstMMRRoot(t *testing.T) {
	for _, n := range []int{1, 2, 3, 5, 7, 11, 16, 23} {
		ls := make([][]byte, n)
		for i := range ls {
			ls[i] = leafAt(i)
		}
		m := build(n)
		tree := merkle.New(ls)
		for i := 0; i < n; i++ {
			tp, err := tree.Proof(i)
			if err != nil {
				t.Fatalf("n=%d i=%d: %v", n, i, err)
			}
			if !tp.Verify(m.Root(), leafAt(i)) {
				t.Errorf("n=%d i=%d: Tendermint proof rejected by the MMR root", n, i)
			}
			mp, err := m.Proof(i)
			if err != nil {
				t.Fatalf("n=%d i=%d: %v", n, i, err)
			}
			if !Verify(tree.Root(), leafAt(i), mp) {
				t.Errorf("n=%d i=%d: MMR proof rejected by the tree root", n, i)
			}
		}
	}
}

func TestPeakStructure(t *testing.T) {
	tests := []struct {
		leaves int
		want   []int
	}{
		{1, []int{0}},
		{2, []int{1}},
		{3, []int{1, 0}},
		{4, []int{2}},
		{7, []int{2, 1, 0}},
		{11, []int{3, 1, 0}},
		{16, []int{4}},
	}
	for _, tc := range tests {
		if got := len(peakHeights(tc.leaves)); got != len(tc.want) {
			t.Errorf("n=%d: %d peaks, want %d", tc.leaves, got, len(tc.want))
			continue
		}
		for i, h := range peakHeights(tc.leaves) {
			if h != tc.want[i] {
				t.Errorf("n=%d: peak %d height %d, want %d", tc.leaves, i, h, tc.want[i])
			}
		}
		if got := len(build(tc.leaves).peaks); got != len(tc.want) {
			t.Errorf("n=%d: MMR built %d peaks, want %d", tc.leaves, got, len(tc.want))
		}
	}
}

func TestRejects(t *testing.T) {
	m := build(11)
	root := m.Root()
	p3, _ := m.Proof(3)
	p7, _ := m.Proof(7)

	tests := []struct {
		name  string
		root  []byte
		leaf  []byte
		proof Proof
	}{
		{"forged leaf", root, []byte("never-appended"), p3},
		{"another real leaf", root, leafAt(4), p3},
		{"proof replayed at another index", root, leafAt(3), Proof{Index: 4, Total: p3.Total, Path: p3.Path, Before: p3.Before, After: p3.After}},
		{"another leaf's proof", root, leafAt(3), p7},
		{"wrong total", root, leafAt(3), Proof{Index: 3, Total: 10, Path: p3.Path, Before: p3.Before, After: p3.After}},
		{"padded path", root, leafAt(3), Proof{Index: 3, Total: 11, Path: append(append([][]byte{}, p3.Path...), make([]byte, HashSize)), Before: p3.Before, After: p3.After}},
		{"truncated path", root, leafAt(3), Proof{Index: 3, Total: 11, Path: p3.Path[:len(p3.Path)-1], Before: p3.Before, After: p3.After}},
		{"peaks swapped", root, leafAt(3), Proof{Index: 3, Total: 11, Path: p3.Path, Before: p3.After, After: p3.Before}},
		{"index beyond total", root, leafAt(3), Proof{Index: 11, Total: 11, Path: p3.Path, Before: p3.Before, After: p3.After}},
		{"negative index", root, leafAt(3), Proof{Index: -1, Total: 11, Path: p3.Path, Before: p3.Before, After: p3.After}},
		{"zero total", root, leafAt(3), Proof{Index: 0, Total: 0}},
		{"short root", root[:31], leafAt(3), p3},
		{"short hash in path", root, leafAt(3), Proof{Index: 3, Total: 11, Path: [][]byte{{1, 2, 3}, p3.Path[1]}, Before: p3.Before, After: p3.After}},
	}
	for _, tc := range tests {
		if Verify(tc.root, tc.leaf, tc.proof) {
			t.Errorf("%s: accepted, must be rejected", tc.name)
		}
	}
}

// A proof is issued against one size. Appending moves the root, and the old
// proof must stop verifying against the new one rather than quietly pass.
func TestProofIsBoundToItsSize(t *testing.T) {
	m := build(5)
	old, _ := m.Proof(2)
	oldRoot := m.Root()
	if !Verify(oldRoot, leafAt(2), old) {
		t.Fatal("proof does not verify against its own root")
	}
	m.Append(leafAt(5))
	if Verify(m.Root(), leafAt(2), old) {
		t.Error("a stale proof verified against the new root")
	}
	fresh, _ := m.Proof(2)
	if !Verify(m.Root(), leafAt(2), fresh) {
		t.Error("a reissued proof does not verify")
	}
	if !Verify(oldRoot, leafAt(2), old) {
		t.Error("the old proof stopped verifying against the old root")
	}
}

func TestEmptyAndRange(t *testing.T) {
	m := New()
	if m.Size() != 0 || m.Root() != nil || m.Nodes() != 0 {
		t.Error("a fresh MMR is not empty")
	}
	if _, err := m.Proof(0); err != ErrEmpty {
		t.Errorf("empty Proof: err = %v, want %v", err, ErrEmpty)
	}
	m.Append(leafAt(0))
	for _, i := range []int{-1, 1, 99} {
		if _, err := m.Proof(i); err != ErrIndexRange {
			t.Errorf("index %d: err = %v, want %v", i, err, ErrIndexRange)
		}
	}
}

// Storage claim from the package doc: 2n - popcount(n) stored hashes.
func TestNodeCount(t *testing.T) {
	for n := 1; n <= 40; n++ {
		want := 2*n - popcount(n)
		if got := build(n).Nodes(); got != want {
			t.Errorf("n=%d: %d nodes, want 2n-popcount(n) = %d", n, got, want)
		}
	}
}

func popcount(n int) int {
	c := 0
	for n != 0 {
		c += n & 1
		n >>= 1
	}
	return c
}

func TestParseProofRoundTrip(t *testing.T) {
	m := build(11)
	for i := 0; i < 11; i++ {
		want, _ := m.Proof(i)
		path, before, after := want.Hex()
		got, err := ParseProof(i, 11, path, before, after)
		if err != nil {
			t.Fatalf("i=%d: ParseProof: %v", i, err)
		}
		if !Verify(m.Root(), leafAt(i), got) {
			t.Errorf("i=%d: reparsed proof does not verify", i)
		}
	}
}

func TestParseProofErrors(t *testing.T) {
	if _, err := ParseProof(0, 2, "zz", "", ""); err != ErrBadHex {
		t.Errorf("bad hex: err = %v", err)
	}
	if _, err := ParseProof(0, 2, "abcd", "", ""); err != ErrBadSize {
		t.Errorf("bad size: err = %v", err)
	}
}

// PeakHashes is the whole verifier-side state, and it must stay logarithmic.
func TestPeakCountIsLogarithmic(t *testing.T) {
	m := build(1023)
	if got := len(m.PeakHashes()); got != 10 {
		t.Errorf("1023 leaves: %d peaks, want 10", got)
	}
	if got := len(build(1024).PeakHashes()); got != 1 {
		t.Errorf("1024 leaves: %d peaks, want 1", got)
	}
}

verify.gno

package mmr

import (
	"encoding/hex"
	"strings"

	"gno.land/p/nym-moultest123/x/merkle/v0"
)

// peakHeights returns the mountain heights of a log of total leaves, left to
// right. They are the set bits of total, high to low: 11 leaves is 8 + 2 + 1,
// so heights 3, 1, 0.
func peakHeights(total int) []int {
	var out []int
	for h := 62; h >= 0; h-- {
		if total&(1<<uint(h)) != 0 {
			out = append(out, h)
		}
	}
	return out
}

// locate returns which mountain holds the leaf at index, and the leaf's index
// within that mountain. It returns -1 when index is out of range.
func locate(total, index int) (int, int) {
	offset := 0
	for j, h := range peakHeights(total) {
		size := 1 << uint(h)
		if index < offset+size {
			return j, index - offset
		}
		offset += size
	}
	return -1, 0
}

// Verify reports whether leaf really sits at p.Index of a log that held
// p.Total leaves and whose root is root.
//
// Every dimension of the proof is checked against p.Total rather than trusted:
// the peak count, which mountain holds the leaf, the local index, the path
// length and both peak-list lengths are all recomputed. A proof that does not
// have exactly the shape p.Total implies is rejected before any hashing.
//
// Failures are false, never a panic, so a realm chooses whether a bad proof
// aborts or branches.
func Verify(root, leaf []byte, p Proof) bool {
	if len(root) != HashSize || p.Total <= 0 || p.Index < 0 || p.Index >= p.Total {
		return false
	}
	heights := peakHeights(p.Total)
	if len(heights) > MaxPeaks {
		return false
	}
	j, local := locate(p.Total, p.Index)
	if j < 0 {
		return false
	}
	if len(p.Path) != heights[j] || len(p.Before) != j || len(p.After) != len(heights)-1-j {
		return false
	}
	if !allHashes(p.Path) || !allHashes(p.Before) || !allHashes(p.After) {
		return false
	}

	node := merkle.LeafHash(leaf)
	for d, sib := range p.Path {
		if (local>>uint(d))&1 == 1 {
			node = merkle.InnerHash(sib, node)
		} else {
			node = merkle.InnerHash(node, sib)
		}
	}

	peaks := make([][]byte, 0, len(heights))
	peaks = append(peaks, p.Before...)
	peaks = append(peaks, node)
	peaks = append(peaks, p.After...)
	return equal(bag(peaks), root)
}

func allHashes(hs [][]byte) bool {
	for _, h := range hs {
		if len(h) != HashSize {
			return false
		}
	}
	return true
}

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

// Hex renders the three hash lists as comma-separated hex, in the order
// path|before|after, which is what a realm call takes as arguments.
func (p Proof) Hex() (path, before, after string) {
	return joinHex(p.Path), joinHex(p.Before), joinHex(p.After)
}

func joinHex(hs [][]byte) string {
	parts := make([]string, len(hs))
	for i, h := range hs {
		parts[i] = hex.EncodeToString(h)
	}
	return strings.Join(parts, ",")
}

// ParseProof rebuilds a Proof from realm-call arguments. Each of path, before
// and after is a comma-separated hex list, possibly empty.
func ParseProof(index, total int, path, before, after string) (Proof, error) {
	ph, err := splitHex(path)
	if err != nil {
		return Proof{}, err
	}
	bh, err := splitHex(before)
	if err != nil {
		return Proof{}, err
	}
	ah, err := splitHex(after)
	if err != nil {
		return Proof{}, err
	}
	if len(bh)+len(ah)+1 > MaxPeaks {
		return Proof{}, ErrTooManyPeaks
	}
	return Proof{Index: index, Total: total, Path: ph, Before: bh, After: ah}, nil
}

func splitHex(s string) ([][]byte, error) {
	s = strings.TrimSpace(s)
	if s == "" {
		return nil, nil
	}
	var out [][]byte
	for _, raw := range strings.Split(s, ",") {
		raw = strings.TrimSpace(raw)
		if raw == "" {
			continue
		}
		b, err := hex.DecodeString(raw)
		if err != nil {
			return nil, ErrBadHex
		}
		if len(b) != HashSize {
			return nil, ErrBadSize
		}
		out = append(out, b)
	}
	return out, nil
}