# Merklist

An associative definition for the hash of an ordered sequence of elements

Matrix multiplication's associativity and non-commutativity properties provide a natural definition for a cryptographic hash / digest / summary of an ordered list of elements while preserving concatenation operations. Due to the non-commutativity property, lists that differ in element order result in a different summary. Due to the associativity property, arbitrarily divided adjacent sub-lists can be summarized independently and combined to find the summary of their concatenation in one operation. This definition provides exactly the properties needed to define a list, and does not impose any unnecessary structure that could cause two equivalent lists to produce different summaries. The name *Merklist* is intended to be reminicent of other hash-based data structures like Merkle Tree and Merklix Tree.

## Definition

This definition of a hash of a list of elements is pretty simple:

- A
**list element**is an arbitrary buffer of bytes. Any length, any content. Just bytes. - A
**list**, then, is a sequence of such elements. - The
**hash of a list element**is the cryptographic hash of its bytes, formatted into a square matrix with byte elements. (More details later.) - The
**hash of a list**is reduction by matrix multiplication of the hashes of all the list elements in the same order as they appear in the list. - The
**hash of a list with 0 elements**is the identity matrix.

This construction has a couple notable concequences:

- The hash of a list with only one item is just the hash of the item itself.
- You can calculate the hash of any list concatenated with a copy of itself by matrix multiplication of the the hash with itself. This works for single elements as well as arbitrarily long lists.
- A list can have multiple copies of the same list item, and swapping them does not affect the list hash. Consider how swapping the first two elements in
`[1, 1, 2]`

has no discernible effect. - The hash of the concatenation of two lists is the matrix multiplication of their hashes.
- Concatenating a list with a list of 0 elements yields the same hash.

Lets explore this definition in more detail with a simple implementation in python+numpy.

```
# Setup and imports
import hashlib
import numpy as np
from functools import reduce
def assert_equal(a, b):
return np.testing.assert_equal(a, b)
def assert_not_equal(a, b):
return np.testing.assert_raises(AssertionError, np.testing.assert_equal, a, b)
```

###
`hash_m/1`

The hash of a list element - The function `hash_m/1`

takes a buffer of bytes as its first argument, and returns the sha512 hash of the bytes formatted as an 8×8 2-d array of 8-bit unsigned integers with wrapping overflow. **We define this hash to be the hash of the list element.** Based on a shallow wikipedia dive, someone familiar with linear algebra might say it's a matrix ring, $R_{256}^{8×8}$. Not coincidentally, sha512 outputs 512 bits = 64 bytes = 8 * 8 array of bytes, how convenient. (In fact, that might even be the primary reason why I chose sha512!)

```
def hash_m(e):
hash_bytes = list(hashlib.sha512(e).digest())[:64] # hash the bytes e, convert the digest into a list of 64 bytes
return np.array(hash_bytes, dtype=np.uint8).reshape((8,8)) # convert the digest bytes into a numpy array with the appropriate data type and shape
```

Lets see it in use:

```
print(hash_m(b"Hello A"))
print()
print(hash_m(b"Hello B"))
```

8×8 seems big compared to 3×3 or 4×4 matrixes, but otherwise everything looks normal. The values are as random as you might expect a cryptographic hash to be, and range from 0-255.

```
def mul_m(he1, he2):
return np.matmul(he1, he2, dtype=np.uint8) # just, like, multiply them
```

Consider an example:

```
# `elements` is a list of 3 elements
elements = [b"A", b"Hello", b"World"]
# first, make a new list with the hash of each element
element_hashes = [hash_m(e) for e in elements]
# get the hash of the list by reducing the hashes by matrix multiplication
list_hash1 = mul_m(mul_m(element_hashes[0], element_hashes[1]), element_hashes[2])
# an alternative way to write the reduction
list_hash2 = reduce(mul_m, element_hashes)
# check that these are equivalent
assert_equal(list_hash1, list_hash2)
```

```
print("List of elements:\n", elements, "\n")
print("List of element hashes:\n", element_hashes, "\n")
print("Merklist hash of the list", elements, ":\n", list_hash1, "\n")
```

What does this give us? Generally speaking, multiplying two square matrixes $M_1×M_2$ gives us at least these two properties:

- Associativity - Associativity enables you to reduce a computation using any partitioning because all partitionings yield the same result. Addition is associative $(1+2)+3 = 1+(2+3)$, subtraction is not $(5-3)-2\neq5-(3-2)$. (Associative property)
- Non-Commutativity - Commutativity allows you to swap elements without affecting the result. Addition is commutative $1+2 = 2+1$, but division is not $1\div2 \neq2\div1$. And neither is matrix multiplication. (Commutative property)

This is an unusual combination of properties for an operation. It's at least not a combination encountered in introductory algebra:

associative | commutative | |
---|---|---|

$a+b$ | ✅ | ✅ |

$a*b$ | ✅ | ✅ |

$a-b$ | ❌ | ❌ |

$a/b$ | ❌ | ❌ |

$a^b$ | ❌ | ❌ |

$M×M$ | ✅ | ❌ |

Upon consideration, these are the exact properties that one would want in order to define the hash of a list of items. Non-commutativity enables the order of elements in the list to be well defined, since swapping different elements produces a different hash. Associativity enables calculating the hash of the list by performing the reduction operations in any order, and you still get the same hash.

Lets sanity-check that these properties can hold for the construction described above. For setup, lets consider the hashes of three elements, $he_1$, $he_2$, and $he_3$:

```
he1 = hash_m(b"A")
he2 = hash_m(b"B")
he3 = hash_m(b"C")
```

```
x = np.matmul(np.matmul(he1, he2), he3)
y = np.matmul(he1, np.matmul(he2, he3))
# observe that they produce the same summary
assert_equal(x, y)
```

```
print(x, "\n\n", y)
```

```
x = np.matmul(he1, he2)
y = np.matmul(he2, he1)
# observe that they produce different summaries
assert_not_equal(x, y)
```

```
print(x, "\n\n", y)
```

```
list1 = [hash_m(b"A") for _ in range(0, 1024)]
hash1 = reduce(mul_m, list1)
# Take a starting element and square/double it 10 times. With 1 starting element over 10 doublings = 1024 elements
hash2 = reduce((lambda m, _ : mul_m(m, m)), range(0, 10), hash_m(b"A"))
# Observe that these two methods of calculating the hash have the same result
assert_equal(hash1, hash2)
# lets call it double
def double_m(m, d=1):
return reduce((lambda m, _ : mul_m(m, m)), range(0, d), m)
assert_equal(hash1, double_m(hash_m(b"A"), 10))
def identity_m():
return np.identity(8, dtype=np.uint8)
# generalize double_m to any length, not just doublings, performed in ln(N) matmuls
def repeat_m(m, n):
res = identity_m()
while n > 0:
# concatenate the current doubling iff the bit representing this doubling is set
if n & 1:
res = mul_m(res, m)
n >>= 1
m = mul_m(m, m) # double matrix m
# print(s)
return res
# repeat_m can do the same as double_m
assert_equal(hash1, repeat_m(hash_m(b"A"), 1024))
# but it can also repeat any number of times
hash3 = reduce(mul_m, (hash_m(b"A") for _ in range(0, 3309)))
assert_equal(hash3, repeat_m(hash_m(b"A"), 3309))
# Even returns a sensible result when requesting 0 elements
assert_equal(identity_m(), repeat_m(hash_m(b"A"), 0))
# make helper for reducing an iterable of hashes
def reduce_m(am):
return reduce(mul_m, am)
```

```
print(hash1, "\n\n", hash2)
```

```
a = hash_m(b"A")
b = hash_m(b"B")
a499 = repeat_m(a, 499)
a500 = repeat_m(a, 500)
# this should work because they're all a's
assert_equal(reduce_m([a, a499]), a500)
assert_equal(reduce_m([a499, a]), a500)
# these are lists of 999 elements of a, with one b at position 500 (x) or 501 (y)
x = reduce_m([a499, b, a500])
y = reduce_m([a500, b, a499])
# shifting the b by one element changed the hash
assert_not_equal(x, y)
```

Flex that associativity - this statement is true and equivalent to the assertion below:

$(a × (a499 × b × a500) × (a500 × b × a499) × a) = (a500 × b × (a500 × a500) × b × a500)$

```
assert_equal(reduce_m([a, x, y, a]), reduce_m([a500, b, repeat_m(a500, 2), b, a500]))
```

## Security

The security of the design of merklist leans on existing cryptographic hash function by the requiring that values that go into the final list digest came from some real hashed preimage, and any implementation can require that the primage of every element must be provided. This means that it's not possible to choose an *arbitrary* element hash as an input to the reduction operation, limiting the blast radius that any specific element can have on the final list digest to the bit fixing that is possible by asic bitcoin miners today. So then the question is if bit fixing is enough to degrade the preimage resistance of the merklist design, and if that is impossible to overcome. (Challenges anyone?)

## Unknowns

This appears to me to be a reasonable way to define the hash of a list. The mathematical description of a list aligns very nicely with the properties offered by matrix multiplication. But is it appropriate to use for the same things that a Merkle Tree would be? The big questions are related to the valuable properties of hash functions:

- Given a merklist summary but not the elements, is it possible to produce a different list of elements that hash to the same summary? (~preimage resistance)
- Given a merklist summary or sublist summaries of it, can you derive the hashes of elements or their order?
- Is it possible to predictably alter the merklist summary by concatenating it with some other sublist of real elements?
- Are there other desirable security properties that would be valuable for a list hash?
- Is there a better choice of hash function as a primitive than sha512?
- Is there a better choice of reduction function that still retains associativity+non-commutativity than simple matmul?
- Is there a more appropriate size than an 8x8 matrix / 64 bytes to represent merklist summaries?

Matrixes are well-studied objects, perhaps some of these questions already have an answer. If *you* know something about deriving a preimage of a matrix ring $R_{256}^{8×8}$ using just multiplication, I would be very interested to know. Given the simplicity of the definition, I wouldn't be surprised if there was already a big wrench in the cogs here.

## What's next?

*If this construction has appropriate security properties*, it seems to be a better merkle tree in all respects. Any use of a merkle tree could be replaced with this, and it could enable use-cases where merkle trees aren't useful. Some examples of what I think might be possible:

- Using a Merklist with a sublist summary tree structure enables creating a $O(1)$-sized 'Merklist Proof' that can verify the addition and subtraction of any number of elements at any single point in the list using only $O(log(N))$ time and $O(log(N))$ static space. As a bonus the proof generator and verifier can have totally different tree structures and can still communicate the proof successfully.
- Using a Merklist summary tree you can create a consistent hash of any ordered key-value store (like a btree) that can be maintained incrementally inline with regular node updates, e.g. as part of a LSM-tree. This could facilitate verification and sync between database replicas.
- The sublist summary tree structure can be as dense or sparse as desired. You could summarize down to pairs of elements akin to a merkle tree, but you could also summarize a compressed sublist of hundreds or even millions of elements with a single hash. Of course, calculating or verifying a proof of changes to the middle of that sublist would require rehashing the whole sublist, but this turns it from a fixed structure into a tuneable parameter.
- If all possible elements had an easily calculatable inverse, that would enable "subtracting" an element by inserting its inverse in front of it. That would basically extend the group from a ring into a field, and might have interesting implications.
- For example you could define a cryptographically-secure rolling hash where advancing either end can be calculated in
`O(1)`

time and space.

- For example you could define a cryptographically-secure rolling hash where advancing either end can be calculated in

To be continued...