Skip to content

OnixLabs.Security.Cryptography.MerkleTree T

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

MerkleTree<T> Class

Represents a generic Merkle tree that retains the original typed leaf values alongside their hashes, enabling both root-hash verification and typed leaf retrieval from the same tree instance.

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

Definition

public abstract partial class MerkleTree<T> : MerkleTree, IValueEquatable<MerkleTree<T>>
    where T : IHashable

Type Parameters

Parameter Description
T The type of the leaf values stored in the tree. Must implement IHashable, which requires a ComputeHash(HashAlgorithm) method. Each leaf's hash is computed from its value during tree construction using the supplied HashAlgorithm.

Remarks

MerkleTree<T> extends MerkleTree by storing the original T values at each leaf node in addition to their computed hashes. This allows GetLeafValues() to reconstruct the original leaf sequence after the tree has been built, while all the hash-based operations — root retrieval, equality, binary conversion, and leaf hash enumeration — behave identically to the non-generic base class.

Use MerkleTree<T> when you need to both verify data integrity (via the root Hash) and retrieve or inspect the original leaf values. Use the non-generic MerkleTree when only the hash structure is needed and you want to avoid the overhead of carrying typed values.

Like MerkleTree, MerkleTree<T> enforces value semantics: two instances are equal when their root hashes are equal. Equality does not compare individual leaf values.

The ToMerkleTree(HashAlgorithm) method converts a MerkleTree<T> into a plain hash-only MerkleTree by re-building the tree from the leaf hashes. This is useful when the typed values are no longer needed and you want to hand off a smaller, allocation-lighter object.

The tree is built from a flat sequence of T leaf values. When the number of leaves is odd, the last leaf is padded with an empty hash node so that every level 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.

Note The constructor of MerkleTree<T> is private, so instances can only be created through MerkleTree<T>.Create or via the non-generic MerkleTree.Create<T> convenience overload.

Examples

Building a typed tree and reading leaf values back

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

// Assume MyRecord implements IHashable
MyRecord[] records =
[
    new MyRecord("alice", 1),
    new MyRecord("bob",   2),
    new MyRecord("carol", 3),
];

using HashAlgorithm sha256 = SHA256.Create();
MerkleTree<MyRecord> tree = MerkleTree.Create(records, sha256);

Console.WriteLine(tree.Hash); // Merkle root

IReadOnlyList<MyRecord> leaves = tree.GetLeafValues();
foreach (MyRecord r in leaves)
    Console.WriteLine(r);

Converting to a hash-only tree

using HashAlgorithm sha256b = SHA256.Create();
MerkleTree hashOnly = tree.ToMerkleTree(sha256b);

Console.WriteLine(hashOnly.Hash == tree.Hash); // true — same root

Comparing two typed trees

using HashAlgorithm sha256 = SHA256.Create();

MerkleTree<MyRecord> treeA = MerkleTree.Create(recordsA, sha256);
MerkleTree<MyRecord> treeB = MerkleTree.Create(recordsB, sha256);

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

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. Inherited from MerkleTree.

Hash

public Hash Hash { get; }

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

Static Methods

Method Returns Description
Create(IEnumerable<T>, HashAlgorithm) MerkleTree<T> Creates a MerkleTree<T> from a sequence of IHashable leaf values.

Create(IEnumerable<T>, HashAlgorithm)

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

Creates a MerkleTree<T> from the specified sequence of IHashable leaf values. Each element is hashed with algorithm to form a leaf node, and branch nodes are constructed bottom-up until a single root remains. Odd leaf counts are padded with an empty hash node.

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.

Instance Methods

Method Returns Description
ToMerkleTree(HashAlgorithm) MerkleTree Returns a hash-only, non-generic MerkleTree built from the leaf hashes of this tree.
GetLeafValues() IReadOnlyList<T> Returns the original leaf values in left-to-right order.
GetLeafHashes() IReadOnlyList<Hash> Returns the leaf hashes in left-to-right order. Inherited from MerkleTree.
CollectLeafHashes(MerkleTree, ICollection<Hash>) void Overrides the base traversal to walk generic branch and leaf nodes. Protected.
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<T>?) bool Determines whether this tree is equal to another MerkleTree<T>.
Equals(object?) bool Determines whether this tree is equal to another object.
GetHashCode() int Returns a hash code derived from the root Hash.

ToMerkleTree(HashAlgorithm)

public MerkleTree ToMerkleTree(HashAlgorithm algorithm)

Constructs a hash-only, non-generic MerkleTree by calling MerkleTree.Create with the leaf hashes returned by GetLeafHashes(). The resulting tree has the same root hash as the current MerkleTree<T> instance (when the same algorithm is used), but does not carry any typed leaf values.

Parameter Type Description
algorithm HashAlgorithm The hash algorithm used to combine nodes when rebuilding the tree.

Returns — A new hash-only MerkleTree derived from the leaf hashes of this instance.

Exceptions

Exception Condition
CryptographicException A hash could not be computed while building the resulting tree.

GetLeafValues()

public IReadOnlyList<T> GetLeafValues()

Traverses the tree and returns the original typed leaf values in left-to-right order. Empty padding nodes are not included.

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


GetLeafHashes()

public IReadOnlyList<Hash> GetLeafHashes()

Traverses the tree and returns the leaf hashes in left-to-right order. Inherited from MerkleTree. 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 override void CollectLeafHashes(MerkleTree current, ICollection<Hash> hashes)

Overrides the base-class traversal to correctly visit MerkleTree<T> branch and leaf nodes. Appends each leaf's hash to hashes in left-to-right order.

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. Satisfies IBinaryConvertible.

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. Satisfies IBinaryConvertible.

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<T>?)

public bool Equals(MerkleTree<T>? other)

Determines whether the current MerkleTree<T> is equal to other. Two instances are equal when they are the same reference, or when their root Hash values are equal. Leaf values are not compared.

Parameter Type Description
other MerkleTree<T>? 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 MerkleTree<T> is equal to obj. Casts obj to MerkleTree and delegates to the base-class equality logic.

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().

Returns — A 32-bit signed integer hash code.

Operators

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

operator ==

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

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


operator !=

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

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

See Also

ONIXLabs .NET Library


Clone this wiki locally