Skip to content

OnixLabs.Security.Cryptography.MerkleTree

Matthew Layton edited this page Nov 15, 2026 · 3 revisions

MerkleTree Class

Represents an immutable Merkle tree of Hash values, where each internal branch node holds the combined hash of its two children and each leaf node holds a single hash. The root Hash property exposes the Merkle root, making it straightforward to verify data integrity.

Namespace OnixLabs.Security.Cryptography
Assembly OnixLabs.Security.Cryptography.dll (NuGet)
Inheritance object → MerkleTree
Implements ICryptoPrimitive<MerkleTree>, IValueEquatable<MerkleTree>, IEquatable<MerkleTree>, IBinaryConvertible
Derived MerkleTree<T>

Definition

public abstract partial class MerkleTree : ICryptoPrimitive<MerkleTree>

Remarks

MerkleTree is the non-generic, hash-only base class for the Merkle tree hierarchy. Instances are created exclusively through the static Create factory methods; direct subclassing from outside the assembly is not permitted because the constructor is internal.

The tree is built from a flat sequence of leaf hashes. When the number of leaves is odd, the last leaf is duplicated with an empty hash node so that every level of the tree contains an even number of nodes. Each pair of adjacent nodes is combined by concatenating their hashes and hashing the result with the supplied HashAlgorithm, producing a single parent node. This process repeats upward until only one node remains: the Merkle root.

Equality is defined by value semantics: two MerkleTree instances are equal when their Hash values are equal. GetHashCode delegates directly to the hash code of the underlying Hash value.

ToString() encodes the root hash as a lowercase hexadecimal string using the invariant culture. The ToString(IFormatProvider) overload accepts any IBaseCodec-compatible format provider, enabling Base58, Base64, and other encodings.

Because MerkleTree implements IBinaryConvertible, the raw bytes of the root hash are accessible via AsReadOnlySpan() and AsReadOnlyMemory() without allocating a copy.

Note MerkleTree enforces a non-empty leaf sequence. Passing an empty collection to any Create overload throws ArgumentException.

The generic subclass MerkleTree<T> extends this type to store the original typed leaf values alongside their hashes, enabling leaf-value retrieval after construction.

Examples

Building a tree from raw hashes and reading the root

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

Hash[] leaves =
[
    Hash.Parse("a3f1..."),
    Hash.Parse("b7c2..."),
    Hash.Parse("d09e..."),
    Hash.Parse("f41a..."),
];

using HashAlgorithm sha256 = SHA256.Create();
MerkleTree tree = MerkleTree.Create(leaves, sha256);

Console.WriteLine(tree.Hash); // root hash as lowercase hex
Console.WriteLine(tree);       // same: ToString() defaults to hex

Verifying a dataset by comparing roots

using System.Security.Cryptography;
using OnixLabs.Security.Cryptography;

using HashAlgorithm sha256 = SHA256.Create();

MerkleTree treeA = MerkleTree.Create(hashesA, sha256);
MerkleTree treeB = MerkleTree.Create(hashesB, sha256);

bool identical = treeA == treeB; // true only when every leaf hash matches

Recovering leaf hashes from a tree

IReadOnlyList<Hash> leafHashes = tree.GetLeafHashes();

foreach (Hash h in leafHashes)
    Console.WriteLine(h);

Properties

Property Type Description
Hash Hash Gets the hash of the current Merkle tree node. For a fully built tree this is the Merkle root.

Hash

public Hash Hash { get; }

Gets the Hash of the current MerkleTree node. After construction this is the Merkle root — the single hash that summarises the entire leaf set.

Methods

Static Methods

Method Returns Description
Create(IEnumerable<Hash>, HashAlgorithm) MerkleTree Creates a Merkle tree from a sequence of raw leaf hashes.
Create<T>(IEnumerable<T>, HashAlgorithm) MerkleTree<T> Creates a generic Merkle tree from a sequence of IHashable leaf values.

Instance Methods

Method Returns Description
GetLeafHashes() IReadOnlyList<Hash> Returns the ordered sequence of leaf hashes contained in the tree.
CollectLeafHashes(MerkleTree, ICollection<Hash>) void Recursively traverses the tree and populates a collection with its leaf hashes. Protected; for use by derived types.
AsReadOnlyMemory() ReadOnlyMemory<byte> Returns the root hash as a read-only memory region.
AsReadOnlySpan() ReadOnlySpan<byte> Returns the root hash as a read-only span.
ToString(IFormatProvider) string Returns a string representation of the root hash using the specified format provider.
ToString() string Returns the root hash as a lowercase hexadecimal string.
Equals(MerkleTree?) bool Determines whether this tree is equal to another MerkleTree.
Equals(object?) bool Determines whether this tree is equal to another object.
GetHashCode() int Returns a hash code derived from the root Hash.

Create(IEnumerable<Hash>, HashAlgorithm)

public static MerkleTree Create(IEnumerable<Hash> leaves, HashAlgorithm algorithm)

Creates a MerkleTree from the specified sequence of leaf hashes. Each element becomes a leaf node; branch nodes are constructed bottom-up by combining adjacent pairs with algorithm until a single root node remains. An odd number of leaves causes the last leaf to be padded with an empty hash node.

Parameter Type Description
leaves IEnumerable<Hash> The leaf hashes from which to build the tree. Must not be empty.
algorithm HashAlgorithm The hash algorithm used to combine adjacent nodes at each level.

Returns — A new MerkleTree whose Hash is the Merkle root of leaves.

Exceptions

Exception Condition
ArgumentException leaves is empty.
CryptographicException A hash could not be computed while building the tree.

Create<T>(IEnumerable<T>, HashAlgorithm)

public static MerkleTree<T> Create<T>(IEnumerable<T> leaves, HashAlgorithm algorithm)
    where T : IHashable

Creates a MerkleTree<T> from the specified sequence of IHashable leaf values. This overload retains the original typed values alongside their hashes; use it when you need to retrieve leaf values from the tree after construction. Delegates to MerkleTree<T>.Create.

Parameter Type Description
leaves IEnumerable<T> The leaf values from which to build the tree. Must not be empty.
algorithm HashAlgorithm The hash algorithm used to hash each leaf value and to combine adjacent nodes at each level.

Returns — A new MerkleTree<T> whose Hash is the Merkle root of the hashed leaf values.

Exceptions

Exception Condition
ArgumentException leaves is empty.
CryptographicException A hash could not be computed while building the tree.

GetLeafHashes()

public IReadOnlyList<Hash> GetLeafHashes()

Traverses the tree and returns the leaf hashes in left-to-right order. Empty padding nodes added during construction to keep the tree balanced are not included in the result.

Returns — An immutable, read-only list of Hash values, one per original leaf. The list is backed by an ImmutableArray<Hash>, and each call builds a new one.


CollectLeafHashes(MerkleTree, ICollection<Hash>)

protected virtual void CollectLeafHashes(MerkleTree current, ICollection<Hash> hashes)

Recursively traverses the subtree rooted at current and appends each leaf hash to hashes. This method is virtual and is overridden by MerkleTree<T> to traverse generic branch and leaf nodes correctly. It is intended for use by subclasses that need to customise leaf collection behaviour.

Parameter Type Description
current MerkleTree The node from which traversal begins.
hashes ICollection<Hash> The collection that receives the discovered leaf hashes.

AsReadOnlyMemory()

public ReadOnlyMemory<byte> AsReadOnlyMemory()

Returns the root hash as a ReadOnlyMemory<byte>, delegating to the underlying Hash value.

Returns — A ReadOnlyMemory<byte> over the root hash bytes.


AsReadOnlySpan()

public ReadOnlySpan<byte> AsReadOnlySpan()

Returns the root hash as a ReadOnlySpan<byte>, delegating to the underlying Hash value. The span does not allocate.

Returns — A ReadOnlySpan<byte> over the root hash bytes.


ToString(IFormatProvider)

public string ToString(IFormatProvider provider)

Returns a string representation of the root hash encoded using provider. Any IBaseCodec-compatible format provider — such as Base16FormatProvider, Base58FormatProvider, or Base64FormatProvider — is accepted.

Parameter Type Description
provider IFormatProvider The format provider that determines the encoding of the output string.

Returns — The root hash bytes encoded as a string according to provider.


ToString()

public override string ToString()

Returns a lowercase hexadecimal string representation of the root hash, using Base16FormatProvider.Invariant.

Returns — The root hash as a lowercase hexadecimal string.


Equals(MerkleTree?)

public bool Equals(MerkleTree? other)

Determines whether the current tree is equal to other. Two trees are equal when they are the same reference, or when their Hash values are equal.

Parameter Type Description
other MerkleTree? The tree to compare with the current instance.

Returns — true if the trees have equal root hashes; otherwise, false.


Equals(object?)

public override bool Equals(object? obj)

Determines whether the current tree is equal to obj. Casts obj to MerkleTree and delegates to Equals(MerkleTree?).

Parameter Type Description
obj object? The object to compare with the current instance.

Returns — true if obj is a MerkleTree with an equal root hash; otherwise, false.


GetHashCode()

public override int GetHashCode()

Returns a hash code for the current tree. Delegates to Hash.GetHashCode(), so two trees that are equal by Equals will return the same hash code.

Returns — A 32-bit signed integer hash code.

Operators

Operator Description
operator == Determines whether two MerkleTree instances are equal.
operator != Determines whether two MerkleTree instances are not equal.

operator ==

public static bool operator ==(MerkleTree? left, MerkleTree? right)

Performs an equality comparison between two MerkleTree instances. Returns true if left and right have equal root hashes. Two null references are considered equal.

operator !=

public static bool operator !=(MerkleTree? left, MerkleTree? right)

Performs an inequality comparison between two MerkleTree instances. Returns true if left and right do not have equal root hashes.

See Also

ONIXLabs .NET Library


Clone this wiki locally