Added generalized index handling functions

This commit is contained in:
vbuterin 2019-07-30 12:15:46 -04:00 committed by GitHub
parent 7e3318318d
commit cf7d65e8ff
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 37 additions and 1 deletions

View File

@ -115,7 +115,7 @@ def get_item_position(typ: Type, index: Union[int, str]) -> Tuple[int, int, int]
raise Exception("Only lists/vectors/containers supported")
def get_generalized_index(typ: Type, path: List[Union[int, str]]) -> int:
def get_generalized_index(typ: Type, path: List[Union[int, str]]) -> GeneralizedIndex:
"""
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.
@ -131,6 +131,42 @@ def get_generalized_index(typ: Type, path: List[Union[int, str]]) -> int:
return root
```
### Helpers for generalized indices
#### `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:
o = o * get_previous_power_of_2(i) + i
return o
```
#### `get_generalized_index_length`
```python
def get_generalized_index_length(index: GeneralizedIndex) -> int:
"""
Returns the length of a path represented by a generalized index.
"""
return log(index)
```
#### `get_generalized_index_bit`
```python
def get_generalized_index_bit(index: GeneralizedIndex, bit: int) -> bool:
"""
Returns the i'th bit of a generalized index.
"""
return (index & (1 << bit)) > 0
```
## Merkle multiproofs
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):