Merkle tree levels, branches and branch folding
Definitionbsv_merkle_treebitcoindata-structuresformal-verificationmerkle-tree
Binary Merkle trees over a list of nodes of an arbitrary type, with a combining function about which nothing is assumed.
level: adjacent pairs become ; an unpaired last node becomes .root:nonefor the empty list,some afor the one-element list , and otherwise the root of the next level.sib: the entry at position (exclusive or) of a level, ornoneif that position is past the end.branch: empty for a list of at most one element; otherwise the sibling of position , followed by the branch of position in the next level.fold: starting from a value at position , each branch entry replaces by if the entry isnone, by if it is and is odd, and by if it is and is even; then is replaced by .
This is a model written for reasoning; it is not a transcription of any particular implementation.
Definition code
/-!
Authors: Gregory J. Ward, Bryan W. Daugherty, Shawn M. Ryan.
Source: https://github.com/codenlighten/bsv-lean-proofs (41c4bfd), Apache-2.0.
-/
namespace Bsv.Merkle
variable {α : Type} (H : α → α → α)
/-- One level up. -/
def level : List α → List α
| [] => []
| [a] => [H a a]
| a :: b :: t => H a b :: level t
theorem length_level : ∀ l : List α, (level H l).length = (l.length + 1) / 2
| [] => by simp [level]
| [_] => by simp [level]
| _ :: _ :: t => by
simp only [level, List.length_cons, length_level t]
omega
/-- The root; `none` only for the empty list. -/
def root : List α → Option α
| [] => none
| [a] => some a
| a :: b :: t => root (level H (a :: b :: t))
termination_by l => l.length
decreasing_by simp only [length_level, List.length_cons]; omega
/-- The entry at position `i ^^^ 1`, or `none` if that is past the end (in
particular when `i` is the unpaired last node, which is combined with
itself). -/
def sib (l : List α) (i : Nat) : Option α := l[i ^^^ 1]?
/-- The branch of the leaf at position `i`. -/
def branch : List α → Nat → List (Option α)
| [], _ => []
| [_], _ => []
| a :: b :: t, i => sib (a :: b :: t) i :: branch (level H (a :: b :: t)) (i / 2)
termination_by l => l.length
decreasing_by simp only [length_level, List.length_cons]; omega
/-- One verifier step. -/
def step (h : α) (s : Option α) (i : Nat) : α :=
match s with
| none => H h h
| some x => if i % 2 = 1 then H x h else H h x
/-- Recompute a root from a leaf, its branch and its position. -/
def fold : α → List (Option α) → Nat → α
| h, [], _ => h
| h, s :: br, i => fold (step H h s i) br (i / 2)
end Bsv.Merkle
Source
Gregory J. Ward, Bryan W. Daugherty, Shawn M. Ryan, BSV Lean proofs (Apache-2.0). https://github.com/codenlighten/bsv-lean-proofs/blob/41c4bfdc5ce4dd9bfbf0e21c77e6586d041261de/BsvLeanProofs/Merkle.lean