Repository navigation
OnixLabs.Security.Cryptography.MerkleTree
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> |
public abstract partial class MerkleTree : ICryptoPrimitive<MerkleTree>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
MerkleTreeenforces a non-empty leaf sequence. Passing an empty collection to anyCreateoverload throwsArgumentException.
The generic subclass MerkleTree<T> extends this type to store the original typed leaf values alongside their hashes, enabling leaf-value retrieval after construction.
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 hexusing 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 matchesIReadOnlyList<Hash> leafHashes = tree.GetLeafHashes();
foreach (Hash h in leafHashes)
Console.WriteLine(h);| Property | Type | Description |
|---|---|---|
Hash |
Hash |
Gets the hash of the current Merkle tree node. For a fully built tree this is the Merkle root. |
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.
| 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. |
| 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. |
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. |
public static MerkleTree<T> Create<T>(IEnumerable<T> leaves, HashAlgorithm algorithm)
where T : IHashableCreates 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. |
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.
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. |
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.
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.
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.
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.
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.
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.
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.
| Operator | Description |
|---|---|
operator == |
Determines whether two MerkleTree instances are equal. |
operator != |
Determines whether two MerkleTree instances are not equal. |
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.
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.
ONIXLabs .NET Library · Repository · NuGet · License (Apache-2.0)
Copyright © ONIXLabs 2020. Licensed under the Apache License, Version 2.0.
- Enumeration<T>
- Optional<T>
- OptionalEqualityComparer<T>
- OptionalExtensions
- Result
- Result<T>
- ResultEqualityComparer<T>
- ResultExtensions
- Specification<T>
- Preconditions
- IValueEquatable<T>
- IValueComparable<T>
- IBinaryConvertible
- ISpanBinaryConvertible
- IMemoryBinaryConvertible
- ArrayExtensions
- ComparableExtensions
- DateTimeExtensions
- ISpanParsableExtensions
- ObjectExtensions
- RandomExtensions
- ReadOnlySequenceExtensions
- ReadOnlySpanExtensions
- StringExtensions
- Base16
- Base32
- Base58
- Base64
- IBaseCodec
- IBaseValue
- IBaseValue<T>
- Base16Codec
- Base32Codec
- Base58Codec
- Base64Codec
- Base16FormatProvider
- Base32FormatProvider
- Base58FormatProvider
- Base64FormatProvider
- EncodingExtensions
- ReadOnlySpanExtensions
- StringBuilderExtensions
- BigDecimal
- BigDecimalEqualityComparer
- BigDecimalOrdinalityComparer
- NumberInfo
- NumberInfoEqualityComparer
- NumberInfoOrdinalityComparer
- Int256
- Int512
- UInt256
- UInt512
- Float128
- Float256
- GenericMath
- NumericsExtensions
- ConversionMode
- ScaleMode
- Hash
- NamedHash
- Sha3
- Sha3Hash224
- Sha3Hash256
- Sha3Hash384
- Sha3Hash512
- Sha3Shake128
- Sha3Shake256
- MerkleTree
- MerkleTree<T>
- PrivateKey
- PublicKey
- NamedPrivateKey
- NamedPublicKey
- EcdhPrivateKey
- EcdhPublicKey
- EcdsaPrivateKey
- EcdsaPublicKey
- EddsaPrivateKey
- EddsaPublicKey
- RsaPrivateKey
- RsaPublicKey
- DigitalSignature
- DigitalSignatureAndPublicKey
- Salt
- Secret
- ICryptoPrimitive<T>
- IHashable
- IEcdhPrivateKey
- IEcdsaPrivateKey
- IEddsaPrivateKey
- IRsaPrivateKey
- IPrivateKeyDerivable<T>
- IPrivateKeyExportable
- IPrivateKeyImportable<T>
- IPrivateKeyPemImportable<T>
- IPrivateKeyPkcs8Exportable
- IPrivateKeyPkcs8Importable<T>
- IPrivateKeyPkcs8PemExportable
- IPrivateKeyRawExportable
- IPrivateKeyRawImportable<T>
- IPrivateKeyRawPemExportable
- IEcdhPublicKey
- IEcdsaPublicKey
- IEddsaPublicKey
- IRsaPublicKey
- IPublicKeyExportable
- IPublicKeyImportable<T>
- IPublicKeyPemExportable
- IPublicKeyPemImportable<T>
- IPublicKeyRawExportable
- IPublicKeyRawImportable<T>
- HashAlgorithmExtensions
- ReadOnlySpanExtensions