2019-05-06 15:30:32 +00:00
# Merkle proof formats
2019-03-15 11:24:59 +00:00
2019-05-06 15:30:32 +00:00
**Notice**: This document is a work-in-progress for researchers and implementers.
## Table of contents
2019-04-14 07:17:09 +00:00
<!-- TOC -->
2019-05-06 15:30:32 +00:00
- [Merkle proof formats ](#merkle-proof-formats )
2019-08-15 07:30:01 +00:00
- [Table of contents ](#table-of-contents )
- [Custom types ](#custom-types )
- [Helpers ](#helpers )
- [Generalized Merkle tree index ](#generalized-merkle-tree-index )
- [SSZ object to index ](#ssz-object-to-index )
- [Helpers for generalized indices ](#helpers-for-generalized-indices )
- [`concat_generalized_indices` ](#concat_generalized_indices )
- [`get_generalized_index_length` ](#get_generalized_index_length )
- [`get_generalized_index_bit` ](#get_generalized_index_bit )
- [`generalized_index_sibling` ](#generalized_index_sibling )
- [`generalized_index_child` ](#generalized_index_child )
- [`generalized_index_parent` ](#generalized_index_parent )
- [Merkle multiproofs ](#merkle-multiproofs )
2019-04-14 07:17:09 +00:00
<!-- /TOC -->
2019-08-15 07:30:01 +00:00
## Custom types
We define the following Python custom types for type hinting and readability:
| Name | SSZ equivalent | Description |
| - | - | - |
| `GeneralizedIndex` | `uint64` | the index of a node in a binary Merkle tree |
## Helpers
```python
def get_next_power_of_two(x: int) -> int:
"""
Get next power of 2 >= the input.
"""
if x < = 2:
return x
elif x % 2 == 0:
return 2 * get_next_power_of_two(x // 2)
else:
return 2 * get_next_power_of_two((x + 1) // 2)
```
```python
def get_previous_power_of_two(x: int) -> int:
"""
Get the previous power of 2 >= the input.
"""
assert x >= 2
return get_next_power_of_two(x) // 2
```
2019-04-14 07:17:09 +00:00
## Generalized Merkle tree index
2019-03-13 07:54:27 +00:00
In a binary Merkle tree, we define a "generalized index" of a node as `2**depth + index` . Visually, this looks as follows:
```
1
2 3
4 5 6 7
...
```
Note that the generalized index has the convenient property that the two children of node `k` are `2k` and `2k+1` , and also that it equals the position of a node in the linear representation of the Merkle tree that's computed by this function:
```python
2019-04-13 08:16:44 +00:00
def merkle_tree(leaves: List[Bytes32]) -> List[Bytes32]:
2019-08-15 07:30:01 +00:00
padded_length = get_next_power_of_two(len(leaves))
o = [Hash()] * padded_length + leaves + [Hash()] * (padded_length - len(leaves))
2019-04-13 08:16:44 +00:00
for i in range(len(leaves) - 1, 0, -1):
o[i] = hash(o[i * 2] + o[i * 2 + 1])
2019-03-13 07:54:27 +00:00
return o
```
We will define Merkle proofs in terms of generalized indices.
2019-04-14 07:17:09 +00:00
## SSZ object to index
2019-03-13 07:54:27 +00:00
We can describe the hash tree of any SSZ object, rooted in `hash_tree_root(object)` , as a binary Merkle tree whose depth may vary. For example, an object `{x: bytes32, y: List[uint64]}` would look as follows:
```
root
/ \
x y_root
/ \
y_data_root len(y)
/ \
/\ /\
.......
```
2019-03-14 13:29:03 +00:00
We can now define a concept of a "path", a way of describing a function that takes as input an SSZ object and outputs some specific (possibly deeply nested) member. For example, `foo -> foo.x` is a path, as are `foo -> len(foo.y)` and `foo -> foo.y[5].w` . We'll describe paths as lists, which can have two representations. In "human-readable form", they are `["x"]` , `["y", "__len__"]` and `["y", 5, "w"]` respectively. In "encoded form", they are lists of `uint64` values, in these cases (assuming the fields of `foo` in order are `x` then `y` , and `w` is the first field of `y[i]` ) `[0]` , `[1, 2**64-1]` , `[1, 5, 0]` .
2019-03-13 07:54:27 +00:00
```python
2019-08-01 14:56:31 +00:00
def item_length(typ: SSZType) -> int:
2019-06-17 15:16:00 +00:00
"""
2019-08-15 07:30:01 +00:00
Return the number of bytes in a basic type, or 32 (a full hash) for compound types.
2019-06-17 15:16:00 +00:00
"""
2019-08-01 14:56:31 +00:00
if issubclass(typ, BasicValue):
2019-06-17 15:16:00 +00:00
return typ.byte_len
2019-03-14 13:29:03 +00:00
else:
2019-06-17 15:16:00 +00:00
return 32
2019-08-15 07:30:01 +00:00
```
```python
def get_elem_type(typ: Union[BaseList, Container], index: Union[int, str]) -> SSZType:
2019-06-17 15:16:00 +00:00
"""
2019-08-15 07:30:01 +00:00
Return the type of the element of an object of the given type with the given index
2019-06-17 15:16:00 +00:00
or member variable name (eg. `7` for `x[7]` , `"foo"` for `x.foo` )
"""
2019-08-15 07:30:01 +00:00
return typ.get_fields()[index] if issubclass(typ, Container) else typ.elem_type
```
2019-08-01 22:11:45 +00:00
2019-08-15 07:30:01 +00:00
```python
2019-08-01 14:56:31 +00:00
def chunk_count(typ: SSZType) -> int:
2019-06-17 15:16:00 +00:00
"""
2019-08-15 07:30:01 +00:00
Return the number of hashes needed to represent the top-level elements in the given type
2019-06-17 15:16:00 +00:00
(eg. `x.foo` or `x[7]` but not `x[7].bar` or `x.foo.baz` ). In all cases except lists/vectors
of basic types, this is simply the number of top-level elements, as each element gets one
hash. For lists/vectors of basic types, it is often fewer because multiple basic elements
can be packed into one 32-byte chunk.
"""
2019-08-02 13:43:42 +00:00
# typ.length describes the limit for list types, or the length for vector types.
2019-08-01 14:56:31 +00:00
if issubclass(typ, BasicValue):
2019-06-17 15:16:00 +00:00
return 1
2019-08-01 14:56:31 +00:00
elif issubclass(typ, Bits):
return (typ.length + 255) // 256
elif issubclass(typ, Elements):
2019-06-17 15:16:00 +00:00
return (typ.length * item_length(typ.elem_type) + 31) // 32
2019-08-01 14:56:31 +00:00
elif issubclass(typ, Container):
2019-06-17 15:16:00 +00:00
return len(typ.get_fields())
2019-08-01 14:56:31 +00:00
else:
raise Exception(f"Type not supported: {typ}")
2019-08-15 07:30:01 +00:00
```
2019-06-17 15:16:00 +00:00
2019-08-15 07:30:01 +00:00
```python
2019-08-01 14:56:31 +00:00
def get_item_position(typ: SSZType, index: Union[int, str]) -> Tuple[int, int, int]:
2019-06-17 15:16:00 +00:00
"""
2019-08-15 07:30:01 +00:00
Return three variables:
(i) the index of the chunk in which the given element of the item is represented;
(ii) the starting byte position within the chunk;
(iii) the ending byte position within the chunk.
For example: for a 6-item list of uint64 values, index=2 will return (0, 16, 24), index=5 will return (1, 8, 16)
2019-06-17 15:16:00 +00:00
"""
2019-08-01 14:56:31 +00:00
if issubclass(typ, Elements):
2019-06-17 15:16:00 +00:00
start = index * item_length(typ.elem_type)
return start // 32, start % 32, start % 32 + item_length(typ.elem_type)
2019-08-01 14:56:31 +00:00
elif issubclass(typ, Container):
2019-06-17 15:16:00 +00:00
return typ.get_field_names().index(index), 0, item_length(get_elem_type(typ, index))
2019-03-13 07:54:27 +00:00
else:
2019-06-17 15:16:00 +00:00
raise Exception("Only lists/vectors/containers supported")
2019-08-15 07:30:01 +00:00
```
2019-06-17 15:16:00 +00:00
2019-08-15 07:30:01 +00:00
```python
def get_generalized_index(typ: SSZType, path: List[Union[int, str]]) -> GeneralizedIndex:
2019-06-17 15:16:00 +00:00
"""
Converts a path (eg. `[7, "foo", 3]` for `x[7].foo[3]` , `[12, "bar", "__len__"]` for
`len(x[12].bar)` ) into the generalized index representing its position in the Merkle tree.
"""
2019-08-01 11:57:34 +00:00
root = 1
2019-06-17 15:16:00 +00:00
for p in path:
2019-08-01 14:56:31 +00:00
assert not issubclass(typ, BasicValue) # If we descend to a basic type, the path cannot continue further
2019-06-17 15:16:00 +00:00
if p == '__len__':
2019-08-01 15:40:40 +00:00
typ, root = uint64, root * 2 + 1 if issubclass(typ, (List, Bytes)) else None
2019-06-17 15:16:00 +00:00
else:
pos, _, _ = get_item_position(typ, p)
2019-08-15 07:30:01 +00:00
root = root * (2 if issubclass(typ, (List, Bytes)) else 1) * get_next_power_of_two(chunk_count(typ)) + pos
2019-06-17 15:16:00 +00:00
typ = get_elem_type(typ, p)
return root
2019-03-13 07:54:27 +00:00
```
2019-07-30 16:15:46 +00:00
### Helpers for generalized indices
2019-08-02 13:57:32 +00:00
_Usage note: functions outside this section should manipulate generalized indices using only functions inside this section. This is to make it easier for developers to implement generalized indices with underlying representations other than bigints._
2019-07-30 16:15:46 +00:00
#### `concat_generalized_indices`
```python
def concat_generalized_indices(*indices: Sequence[GeneralizedIndex]) -> GeneralizedIndex:
"""
Given generalized indices i1 for A -> B, i2 for B -> C .... i_n for Y -> Z, returns
the generalized index for A -> Z.
"""
o = GeneralizedIndex(1)
for i in indices:
2019-08-15 07:30:01 +00:00
o = o * get_previous_power_of_two(i) + (i - get_previous_power_of_two(i))
2019-07-30 16:15:46 +00:00
return o
```
#### `get_generalized_index_length`
```python
def get_generalized_index_length(index: GeneralizedIndex) -> int:
2019-08-15 07:30:01 +00:00
"""
Return the length of a path represented by a generalized index.
"""
return log2(index)
2019-07-30 16:15:46 +00:00
```
#### `get_generalized_index_bit`
```python
2019-08-01 22:11:30 +00:00
def get_generalized_index_bit(index: GeneralizedIndex, position: int) -> bool:
2019-08-15 07:30:01 +00:00
"""
Return the given bit of a generalized index.
"""
return (index & (1 < < position ) ) > 0
2019-08-01 22:11:30 +00:00
```
#### `generalized_index_sibling`
```python
def generalized_index_sibling(index: GeneralizedIndex) -> GeneralizedIndex:
2019-08-15 07:30:01 +00:00
return index ^ 1
2019-08-01 22:11:30 +00:00
```
#### `generalized_index_child`
```python
def generalized_index_child(index: GeneralizedIndex, right_side: bool) -> GeneralizedIndex:
2019-08-15 07:30:01 +00:00
return index * 2 + right_side
2019-08-01 22:11:30 +00:00
```
#### `generalized_index_parent`
```python
def generalized_index_parent(index: GeneralizedIndex) -> GeneralizedIndex:
2019-08-15 07:30:01 +00:00
return index // 2
2019-07-30 16:15:46 +00:00
```
2019-04-14 07:17:09 +00:00
## Merkle multiproofs
2019-03-13 07:54:27 +00:00
2019-04-20 06:01:06 +00:00
We define a Merkle multiproof as a minimal subset of nodes in a Merkle tree needed to fully authenticate that a set of nodes actually are part of a Merkle tree with some specified root, at a particular set of generalized indices. For example, here is the Merkle multiproof for positions 0, 1, 6 in an 8-node Merkle tree (i.e. generalized indices 8, 9, 14):
2019-03-13 07:54:27 +00:00
```
.
. .
. * * .
x x . . . . x *
```
. are unused nodes, * are used nodes, x are the values we are trying to prove. Notice how despite being a multiproof for 3 values, it requires only 3 auxiliary nodes, only one node more than would be required to prove a single value. Normally the efficiency gains are not quite that extreme, but the savings relative to individual Merkle proofs are still significant. As a rule of thumb, a multiproof for k nodes at the same level of an n-node tree has size `k * (n/k + log(n/k))`.
2019-06-17 15:16:00 +00:00
First, we provide a method for computing the generalized indices of the auxiliary tree nodes that a proof of a given set of generalized indices will require:
2019-03-13 07:54:27 +00:00
2019-08-02 13:43:03 +00:00
```python
2019-08-01 22:11:30 +00:00
def get_branch_indices(tree_index: GeneralizedIndex) -> List[GeneralizedIndex]:
2019-06-17 15:16:00 +00:00
"""
Get the generalized indices of the sister chunks along the path from the chunk with the
given tree index to the root.
"""
2019-08-01 22:11:30 +00:00
o = [generalized_index_sibling(tree_index)]
2019-06-17 15:16:00 +00:00
while o[-1] > 1:
2019-08-01 22:11:30 +00:00
o.append(generalized_index_sibling(generalized_index_parent(o[-1])))
2019-06-17 15:16:00 +00:00
return o[:-1]
2019-08-15 07:30:01 +00:00
```
2019-06-17 15:16:00 +00:00
2019-08-15 07:30:01 +00:00
```python
2019-08-01 22:11:30 +00:00
def get_helper_indices(indices: List[GeneralizedIndex]) -> List[GeneralizedIndex]:
2019-06-17 15:16:00 +00:00
"""
2019-08-01 22:11:30 +00:00
Get the generalized indices of all "extra" chunks in the tree needed to prove the chunks with the given
generalized indices. Note that the decreasing order is chosen deliberately to ensure equivalence to the
order of hashes in a regular single-item Merkle proof in the single-item case.
2019-06-17 15:16:00 +00:00
"""
2019-08-01 22:11:30 +00:00
all_indices = set()
2019-06-17 15:16:00 +00:00
for index in indices:
2019-08-01 22:11:30 +00:00
all_indices = all_indices.union(set(get_branch_indices(index) + [index]))
2019-08-15 07:30:01 +00:00
2019-08-01 22:11:30 +00:00
return sorted([
x for x in all_indices if not
(generalized_index_child(x, 0) in all_indices and generalized_index_child(x, 1) in all_indices) and not
(x in indices)
2019-08-14 21:44:19 +00:00
], reverse=True)
2019-04-13 08:16:44 +00:00
```
2019-03-13 07:54:27 +00:00
2019-08-01 22:11:30 +00:00
Now we provide the Merkle proof verification functions. First, for single item proofs:
```python
def verify_merkle_proof(leaf: Hash, proof: Sequence[Hash], index: GeneralizedIndex, root: Hash) -> bool:
assert len(proof) == get_generalized_index_length(index)
for i, h in enumerate(proof):
if get_generalized_index_bit(index, i):
leaf = hash(h + leaf)
else:
leaf = hash(leaf + h)
return leaf == root
```
2019-03-13 07:54:27 +00:00
2019-08-01 22:11:30 +00:00
Now for multi-item proofs:
2019-03-14 13:29:03 +00:00
2019-03-13 07:54:27 +00:00
```python
2019-08-15 07:30:01 +00:00
def verify_merkle_multiproof(leaves: Sequence[Hash],
proof: Sequence[Hash],
indices: Sequence[GeneralizedIndex],
root: Hash) -> bool:
2019-08-01 22:11:30 +00:00
assert len(leaves) == len(indices)
helper_indices = get_helper_indices(indices)
assert len(proof) == len(helper_indices)
objects = {
2019-08-15 07:30:01 +00:00
** {index: node for index, node in zip(indices, leaves)},
** {index: node for index, node in zip(helper_indices, proof)}
2019-08-01 22:11:30 +00:00
}
2019-08-14 21:44:26 +00:00
keys = sorted(objects.keys(), reverse=True)
2019-06-17 15:16:00 +00:00
pos = 0
while pos < len ( keys ) :
k = keys[pos]
if k in objects and k ^ 1 in objects and k // 2 not in objects:
2019-08-02 13:46:59 +00:00
objects[k // 2] = hash(objects[(k | 1) ^ 1] + objects[k | 1])
2019-06-17 15:16:00 +00:00
keys.append(k // 2)
pos += 1
2019-08-01 22:11:30 +00:00
return objects[1] == root
2019-06-17 15:16:00 +00:00
```
2019-03-13 07:54:27 +00:00
2019-08-01 22:11:30 +00:00
Note that the single-item proof is a special case of a multi-item proof; a valid single-item proof verifies correctly when put into the multi-item verification function (making the natural trivial changes to input arguments, `index -> [index]` and `leaf -> [leaf]` ).