From 2bda58fbdcd54355d035096d863e92279fe79664 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Thu, 11 Apr 2019 17:13:45 +1000 Subject: [PATCH 1/9] Clean up light client spec --- specs/light_client/merkle_proofs.md | 36 ++++++++++++++--------------- specs/light_client/sync_protocol.md | 21 +++++++++-------- 2 files changed, 30 insertions(+), 27 deletions(-) diff --git a/specs/light_client/merkle_proofs.md b/specs/light_client/merkle_proofs.md index 285445ca85..a3c8fa1543 100644 --- a/specs/light_client/merkle_proofs.md +++ b/specs/light_client/merkle_proofs.md @@ -47,33 +47,33 @@ y_data_root len(y) 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]`. ```python -def path_to_encoded_form(obj: Any, path: List[str or int]) -> List[int]: +def path_to_encoded_form(obj: Any, path: List[Union[str, int]]) -> List[int]: if len(path) == 0: return [] - if isinstance(path[0], "__len__"): + elif isinstance(path[0], "__len__"): assert len(path) == 1 return [LENGTH_FLAG] elif isinstance(path[0], str) and hasattr(obj, "fields"): return [list(obj.fields.keys()).index(path[0])] + path_to_encoded_form(getattr(obj, path[0]), path[1:]) - elif isinstance(obj, (StaticList, DynamicList)): + elif isinstance(obj, (Vector, List)): return [path[0]] + path_to_encoded_form(obj[path[0]], path[1:]) else: raise Exception("Unknown type / path") ``` -We can now define a function `get_generalized_indices(object: Any, path: List[int], root=1: int) -> int` that converts an object and a path to a set of generalized indices (note that for constant-sized objects, there is only one generalized index and it only depends on the path, but for dynamically sized objects the indices may depend on the object itself too). For dynamically-sized objects, the set of indices will have more than one member because of the need to access an array's length to determine the correct generalized index for some array access. +We can now define a function `get_generalized_indices(object: Any, path: List[int], root: int=1) -> List[int]` that converts an object and a path to a set of generalized indices (note that for constant-sized objects, there is only one generalized index and it only depends on the path, but for dynamically sized objects the indices may depend on the object itself too). For dynamically-sized objects, the set of indices will have more than one member because of the need to access an array's length to determine the correct generalized index for some array access. ```python -def get_generalized_indices(obj: Any, path: List[int], root=1) -> List[int]: +def get_generalized_indices(obj: Any, path: List[int], root: int=1) -> List[int]: if len(path) == 0: return [root] - elif isinstance(obj, StaticList): + elif isinstance(obj, Vector): items_per_chunk = (32 // len(serialize(x))) if isinstance(x, int) else 1 new_root = root * next_power_of_2(len(obj) // items_per_chunk) + path[0] // items_per_chunk return get_generalized_indices(obj[path[0]], path[1:], new_root) - elif isinstance(obj, DynamicList) and path[0] == LENGTH_FLAG: + elif isinstance(obj, List) and path[0] == LENGTH_FLAG: return [root * 2 + 1] - elif isinstance(obj, DynamicList) and isinstance(path[0], int): + elif isinstance(obj, List) and isinstance(path[0], int): assert path[0] < len(obj) items_per_chunk = (32 // len(serialize(x))) if isinstance(x, int) else 1 new_root = root * 2 * next_power_of_2(len(obj) // items_per_chunk) + path[0] // items_per_chunk @@ -137,19 +137,19 @@ Generating a proof is simply a matter of taking the node of the SSZ hash tree wi Here is the verification function: ```python -def verify_multi_proof(root, indices, leaves, proof): +def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], proof: List[bytes]): tree = {} for index, leaf in zip(indices, leaves): tree[index] = leaf for index, proofitem in zip(get_proof_indices(indices), proof): tree[index] = proofitem - indexqueue = sorted(tree.keys())[:-1] + index_queue = sorted(tree.keys())[:-1] i = 0 - while i < len(indexqueue): - index = indexqueue[i] - if index >= 2 and index^1 in tree: - tree[index//2] = hash(tree[index - index%2] + tree[index - index%2 + 1]) - indexqueue.append(index//2) + while i < len(index_queue): + index = index_queue[i] + if index >= 2 and index ^ 1 in tree: + tree[index // 2] = hash(tree[index - index % 2] + tree[index - index % 2 + 1]) + index_queue.append(index // 2) i += 1 return (indices == []) or (1 in tree and tree[1] == root) ``` @@ -158,7 +158,7 @@ def verify_multi_proof(root, indices, leaves, proof): We define: -#### `MerklePartial` +#### `SSZMerklePartial` ```python @@ -172,6 +172,6 @@ We define: #### Proofs for execution -We define `MerklePartial(f, arg1, arg2..., focus=0)` as being a `MerklePartial` object wrapping a Merkle multiproof of the set of nodes in the hash tree of the SSZ object `arg[focus]` that is needed to authenticate the parts of the object needed to compute `f(arg1, arg2...)`. +We define `MerklePartial(f, arg1, arg2..., focus=0)` as being a `SSZMerklePartial` object wrapping a Merkle multiproof of the set of nodes in the hash tree of the SSZ object `arg[focus]` that is needed to authenticate the parts of the object needed to compute `f(arg1, arg2...)`. -Ideally, any function which accepts an SSZ object should also be able to accept a `MerklePartial` object as a substitute. +Ideally, any function which accepts an SSZ object should also be able to accept a `SSZMerklePartial` object as a substitute. diff --git a/specs/light_client/sync_protocol.md b/specs/light_client/sync_protocol.md index 94ab8a2e46..7db02050e4 100644 --- a/specs/light_client/sync_protocol.md +++ b/specs/light_client/sync_protocol.md @@ -5,16 +5,19 @@ __NOTICE__: This document is a work-in-progress for researchers and implementers ## Table of Contents + - [Beacon Chain Light Client Syncing](#beacon-chain-light-client-syncing) - [Table of Contents](#table-of-contents) - - [Light client state](#light-client-state) - - [Updating the shuffled committee](#updating-the-shuffled-committee) - - [Computing the current committee](#computing-the-current-committee) - - [Verifying blocks](#verifying-blocks) + - [Preliminaries](#preliminaries) + - [Light client state](#light-client-state) + - [Updating the shuffled committee](#updating-the-shuffled-committee) + - [Computing the current committee](#computing-the-current-committee) + - [Verifying blocks](#verifying-blocks) + -### Preliminaries +## Preliminaries We define an "expansion" of an object as an object where a field in an object that is meant to represent the `hash_tree_root` of another object is replaced by the object. Note that defining expansions is not a consensus-layer-change; it is merely a "re-interpretation" of the object. Particularly, the `hash_tree_root` of an expansion of an object is identical to that of the original object, and we can define expansions where, given a complete history, it is always possible to compute the expansion of any object in the history. The opposite of an expansion is a "summary" (eg. `BeaconBlockHeader` is a summary of `BeaconBlock`). @@ -85,7 +88,7 @@ later_period_data = get_period_data(new_committee_proof, finalized_header, shard The maximum size of a proof is `128 * ((22-7) * 32 + 110) = 75520` bytes for validator records and `(22-7) * 32 + 128 * 8 = 1504` for the active index proof (much smaller because the relevant active indices are all beside each other in the Merkle tree). This needs to be done once per `PERSISTENT_COMMITTEE_PERIOD` epochs (2048 epochs / 9 days), or ~38 bytes per epoch. -### Computing the current committee +## Computing the current committee Here is a helper to compute the committee at a slot given the maximal earlier and later committees: @@ -134,16 +137,16 @@ def compute_committee(header: BeaconBlockHeader, Note that this method makes use of the fact that the committee for any given shard always starts and ends at the same validator index independently of the committee count (this is because the validator set is split into `SHARD_COUNT * committee_count` slices but the first slice of a shard is a multiple `committee_count * i`, so the start of the slice is `n * committee_count * i // (SHARD_COUNT * committee_count) = n * i // SHARD_COUNT`, using the slightly nontrivial algebraic identity `(x * a) // ab == x // b`). -### Verifying blocks +## Verifying blocks If a client wants to update its `finalized_header` it asks the network for a `BlockValidityProof`, which is simply: ```python { - 'header': BlockHeader, + 'header': BeaconBlockHeader, 'shard_aggregate_signature': 'bytes96', 'shard_bitfield': 'bytes', - 'shard_parent_block': ShardBlock + 'shard_parent_block': ShardBlock, } ``` From 8807781a8dd22c73865bd9d6deb9c368bfca3484 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sat, 13 Apr 2019 18:16:44 +1000 Subject: [PATCH 2/9] formatting --- specs/light_client/merkle_proofs.md | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/specs/light_client/merkle_proofs.md b/specs/light_client/merkle_proofs.md index a3c8fa1543..47195b2ca3 100644 --- a/specs/light_client/merkle_proofs.md +++ b/specs/light_client/merkle_proofs.md @@ -20,10 +20,10 @@ In a binary Merkle tree, we define a "generalized index" of a node as `2**depth 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 -def merkle_tree(leaves): +def merkle_tree(leaves: List[Bytes32]) -> List[Bytes32]: o = [0] * len(leaves) + leaves - for i in range(len(leaves)-1, 0, -1): - o[i] = hash(o[i*2] + o[i*2+1]) + for i in range(len(leaves) - 1, 0, -1): + o[i] = hash(o[i * 2] + o[i * 2 + 1]) return o ``` @@ -102,8 +102,8 @@ x x . . . . x * Here is code for creating and verifying a multiproof. First a helper: ```python -def log2(x): - return 0 if x == 1 else 1 + log2(x//2) +def log2(x: int) -> int: + return 0 if x == 1 else 1 + log2(x // 2) ``` First, a method for computing the generalized indices of the auxiliary tree nodes that a proof of a given set of generalized indices will require: @@ -111,7 +111,7 @@ First, a method for computing the generalized indices of the auxiliary tree node ```python def get_proof_indices(tree_indices: List[int]) -> List[int]: # Get all indices touched by the proof - maximal_indices = set({}) + maximal_indices = set() for i in tree_indices: x = i while x > 1: @@ -119,7 +119,7 @@ def get_proof_indices(tree_indices: List[int]) -> List[int]: x //= 2 maximal_indices = tree_indices + sorted(list(maximal_indices))[::-1] # Get indices that cannot be recalculated from earlier indices - redundant_indices = set({}) + redundant_indices = set() proof = [] for index in maximal_indices: if index not in redundant_indices: @@ -130,19 +130,19 @@ def get_proof_indices(tree_indices: List[int]) -> List[int]: break index //= 2 return [i for i in proof if i not in tree_indices] -```` +``` Generating a proof is simply a matter of taking the node of the SSZ hash tree with the union of the given generalized indices for each index given by `get_proof_indices`, and outputting the list of nodes in the same order. Here is the verification function: ```python -def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], proof: List[bytes]): +def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], proof: List[bytes]) -> bool: tree = {} for index, leaf in zip(indices, leaves): tree[index] = leaf - for index, proofitem in zip(get_proof_indices(indices), proof): - tree[index] = proofitem + for index, proof_item in zip(get_proof_indices(indices), proof): + tree[index] = proof_item index_queue = sorted(tree.keys())[:-1] i = 0 while i < len(index_queue): From 449e8a44a4e9c3040334cac58b204d9ebede0951 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sat, 13 Apr 2019 18:17:09 +1000 Subject: [PATCH 3/9] Remove unused `log2` --- specs/light_client/merkle_proofs.md | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/specs/light_client/merkle_proofs.md b/specs/light_client/merkle_proofs.md index 47195b2ca3..371f0ffdee 100644 --- a/specs/light_client/merkle_proofs.md +++ b/specs/light_client/merkle_proofs.md @@ -99,14 +99,7 @@ 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))`. -Here is code for creating and verifying a multiproof. First a helper: - -```python -def log2(x: int) -> int: - return 0 if x == 1 else 1 + log2(x // 2) -``` - -First, a method for computing the generalized indices of the auxiliary tree nodes that a proof of a given set of generalized indices will require: +Here is code for creating and verifying a multiproof. First, a method for computing the generalized indices of the auxiliary tree nodes that a proof of a given set of generalized indices will require: ```python def get_proof_indices(tree_indices: List[int]) -> List[int]: From 705b553139c5e8cb523a62010e76850a85054b68 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sun, 14 Apr 2019 12:11:50 +1000 Subject: [PATCH 4/9] Fix --- specs/light_client/sync_protocol.md | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/specs/light_client/sync_protocol.md b/specs/light_client/sync_protocol.md index 7db02050e4..795c057ab3 100644 --- a/specs/light_client/sync_protocol.md +++ b/specs/light_client/sync_protocol.md @@ -43,7 +43,7 @@ We add a data type `PeriodData` and four helpers: { 'validator_count': 'uint64', 'seed': 'bytes32', - 'committee': [Validator] + 'committee': [Validator], } ``` @@ -94,8 +94,7 @@ Here is a helper to compute the committee at a slot given the maximal earlier an ```python def compute_committee(header: BeaconBlockHeader, - validator_memory: ValidatorMemory): - + validator_memory: ValidatorMemory) -> List[ValidatorIndex]: earlier_validator_count = validator_memory.earlier_period_data.validator_count later_validator_count = validator_memory.later_period_data.validator_count maximal_earlier_committee = validator_memory.earlier_period_data.committee @@ -108,11 +107,13 @@ def compute_committee(header: BeaconBlockHeader, earlier_validator_count // (SHARD_COUNT * TARGET_COMMITTEE_SIZE), later_validator_count // (SHARD_COUNT * TARGET_COMMITTEE_SIZE), ) + 1 - - def get_offset(count, end:bool): - return get_split_offset(count, - SHARD_COUNT * committee_count, - validator_memory.shard_id * committee_count + (1 if end else 0)) + + def get_offset(count: int, end: bool) -> int: + return get_split_offset( + count, + SHARD_COUNT * committee_count, + validator_memory.shard_id * committee_count + (1 if end else 0), + ) actual_earlier_committee = maximal_earlier_committee[ 0:get_offset(earlier_validator_count, True) - get_offset(earlier_validator_count, False) @@ -132,7 +133,6 @@ def compute_committee(header: BeaconBlockHeader, [i for i in earlier_committee if epoch % PERSISTENT_COMMITTEE_PERIOD < get_switchover_epoch(i)] + [i for i in later_committee if epoch % PERSISTENT_COMMITTEE_PERIOD >= get_switchover_epoch(i)] ))) - ``` Note that this method makes use of the fact that the committee for any given shard always starts and ends at the same validator index independently of the committee count (this is because the validator set is split into `SHARD_COUNT * committee_count` slices but the first slice of a shard is a multiple `committee_count * i`, so the start of the slice is `n * committee_count * i // (SHARD_COUNT * committee_count) = n * i // SHARD_COUNT`, using the slightly nontrivial algebraic identity `(x * a) // ab == x // b`). From 5ed4cb29f6b62887b42db4a4651389594805d9e5 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sun, 14 Apr 2019 12:15:24 +1000 Subject: [PATCH 5/9] ValidatorMemory --- specs/light_client/sync_protocol.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/light_client/sync_protocol.md b/specs/light_client/sync_protocol.md index 795c057ab3..9857968638 100644 --- a/specs/light_client/sync_protocol.md +++ b/specs/light_client/sync_protocol.md @@ -75,7 +75,7 @@ A light client will keep track of: * `later_period_data = get_period_data(finalized_header, shard_id, later=True)` * `earlier_period_data = get_period_data(finalized_header, shard_id, later=False)` -We use the struct `validator_memory` to keep track of these variables. +We use the struct `ValidatorMemory` to keep track of these variables. ### Updating the shuffled committee From f7d3e02eb254749913e3ed652b890983291a153a Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sun, 14 Apr 2019 17:17:09 +1000 Subject: [PATCH 6/9] Add ToC --- specs/light_client/merkle_proofs.md | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/specs/light_client/merkle_proofs.md b/specs/light_client/merkle_proofs.md index 371f0ffdee..46fa23f828 100644 --- a/specs/light_client/merkle_proofs.md +++ b/specs/light_client/merkle_proofs.md @@ -1,12 +1,26 @@ **NOTICE**: This document is a work-in-progress for researchers and implementers. -### Constants +## Table of Contents + + +- [Table of Contents](#table-of-contents) +- [Constants](#constants) +- [Generalized Merkle tree index](#generalized-merkle-tree-index) +- [SSZ object to index](#ssz-object-to-index) +- [Merkle multiproofs](#merkle-multiproofs) +- [MerklePartial](#merklepartial) + - [`SSZMerklePartial`](#sszmerklepartial) + - [Proofs for execution](#proofs-for-execution) + + + +## Constants | Name | Value | | - | - | | `LENGTH_FLAG` | `2**64 - 1` | -### Generalized Merkle tree index +## Generalized Merkle tree index In a binary Merkle tree, we define a "generalized index" of a node as `2**depth + index`. Visually, this looks as follows: @@ -29,7 +43,7 @@ def merkle_tree(leaves: List[Bytes32]) -> List[Bytes32]: We will define Merkle proofs in terms of generalized indices. -### SSZ object to index +## SSZ object to index 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: @@ -86,7 +100,7 @@ def get_generalized_indices(obj: Any, path: List[int], root: int=1) -> List[int] raise Exception("Unknown type / path") ``` -### Merkle multiproofs +## 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 (ie. generalized indices 8, 9, 14): @@ -147,11 +161,11 @@ def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], return (indices == []) or (1 in tree and tree[1] == root) ``` -### MerklePartial +## MerklePartial We define: -#### `SSZMerklePartial` +### `SSZMerklePartial` ```python @@ -163,7 +177,7 @@ We define: } ``` -#### Proofs for execution +### Proofs for execution We define `MerklePartial(f, arg1, arg2..., focus=0)` as being a `SSZMerklePartial` object wrapping a Merkle multiproof of the set of nodes in the hash tree of the SSZ object `arg[focus]` that is needed to authenticate the parts of the object needed to compute `f(arg1, arg2...)`. From 2f2e7847de10e4b424b885108936f5aaacca4dac Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sun, 14 Apr 2019 18:13:43 +1000 Subject: [PATCH 7/9] More fix --- specs/light_client/sync_protocol.md | 63 ++++++++++++++++++++--------- 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/specs/light_client/sync_protocol.md b/specs/light_client/sync_protocol.md index 9857968638..3850f077de 100644 --- a/specs/light_client/sync_protocol.md +++ b/specs/light_client/sync_protocol.md @@ -9,6 +9,13 @@ __NOTICE__: This document is a work-in-progress for researchers and implementers - [Beacon Chain Light Client Syncing](#beacon-chain-light-client-syncing) - [Table of Contents](#table-of-contents) - [Preliminaries](#preliminaries) + - [Expansions](#expansions) + - [`get_active_validator_indices`](#get_active_validator_indices) + - [`MerklePartial`](#merklepartial) + - [`PeriodData`](#perioddata) + - [`get_earlier_start_epoch`](#get_earlier_start_epoch) + - [`get_later_start_epoch`](#get_later_start_epoch) + - [`get_period_data`](#get_period_data) - [Light client state](#light-client-state) - [Updating the shuffled committee](#updating-the-shuffled-committee) - [Computing the current committee](#computing-the-current-committee) @@ -16,28 +23,34 @@ __NOTICE__: This document is a work-in-progress for researchers and implementers - ## Preliminaries +### Expansions + We define an "expansion" of an object as an object where a field in an object that is meant to represent the `hash_tree_root` of another object is replaced by the object. Note that defining expansions is not a consensus-layer-change; it is merely a "re-interpretation" of the object. Particularly, the `hash_tree_root` of an expansion of an object is identical to that of the original object, and we can define expansions where, given a complete history, it is always possible to compute the expansion of any object in the history. The opposite of an expansion is a "summary" (eg. `BeaconBlockHeader` is a summary of `BeaconBlock`). We define two expansions: -* `ExtendedBeaconBlock`, which is identical to a `BeaconBlock` except `state_root` is replaced with the corresponding `state: ExtendedBeaconState` -* `ExtendedBeaconState`, which is identical to a `BeaconState` except `latest_active_index_roots: List[Bytes32]` is replaced by `latest_active_indices: List[List[ValidatorIndex]]`, where `BeaconState.latest_active_index_roots[i] = hash_tree_root(ExtendedBeaconState.latest_active_indices[i])` +* `ExtendedBeaconState`, which is identical to a `BeaconState` except `latest_active_index_roots: List[Bytes32]` is replaced by `latest_active_indices: List[List[ValidatorIndex]]`, where `BeaconState.latest_active_index_roots[i] = hash_tree_root(ExtendedBeaconState.latest_active_indices[i])`. +* `ExtendedBeaconBlock`, which is identical to a `BeaconBlock` except `state_root` is replaced with the corresponding `state: ExtendedBeaconState`. + +### `get_active_validator_indices` Note that there is now a new way to compute `get_active_validator_indices`: ```python -def get_active_validator_indices(state: BeaconState, epoch: Epoch) -> List[ValidatorIndex]: +def get_active_validator_indices(state: ExtendedBeaconState, epoch: Epoch) -> List[ValidatorIndex]: return state.latest_active_indices[epoch % LATEST_ACTIVE_INDEX_ROOTS_LENGTH] ``` Note that it takes `state` instead of `state.validator_registry` as an argument. This does not affect its use in `get_shuffled_committee`, because `get_shuffled_committee` has access to the full `state` as one of its arguments. + +### `MerklePartial` + A `MerklePartial(f, *args)` is an object that contains a minimal Merkle proof needed to compute `f(*args)`. A `MerklePartial` can be used in place of a regular SSZ object, though a computation would return an error if it attempts to access part of the object that is not contained in the proof. -We add a data type `PeriodData` and four helpers: +### `PeriodData` ```python { @@ -47,13 +60,23 @@ We add a data type `PeriodData` and four helpers: } ``` +### `get_earlier_start_epoch` + ```python def get_earlier_start_epoch(slot: Slot) -> int: return slot - slot % PERSISTENT_COMMITTEE_PERIOD - PERSISTENT_COMMITTEE_PERIOD * 2 - +``` + +### `get_later_start_epoch` + +```python def get_later_start_epoch(slot: Slot) -> int: return slot - slot % PERSISTENT_COMMITTEE_PERIOD - PERSISTENT_COMMITTEE_PERIOD - +``` + +### `get_period_data` + +```python def get_period_data(block: ExtendedBeaconBlock, shard_id: Shard, later: bool) -> PeriodData: period_start = get_later_start_epoch(header.slot) if later else get_earlier_start_epoch(header.slot) validator_count = len(get_active_validator_indices(state, period_start)) @@ -62,7 +85,7 @@ def get_period_data(block: ExtendedBeaconBlock, shard_id: Shard, later: bool) -> return PeriodData( validator_count, generate_seed(block.state, period_start), - [block.state.validator_registry[i] for i in indices] + [block.state.validator_registry[i] for i in indices], ) ``` @@ -114,7 +137,7 @@ def compute_committee(header: BeaconBlockHeader, SHARD_COUNT * committee_count, validator_memory.shard_id * committee_count + (1 if end else 0), ) - + actual_earlier_committee = maximal_earlier_committee[ 0:get_offset(earlier_validator_count, True) - get_offset(earlier_validator_count, False) ] @@ -123,15 +146,15 @@ def compute_committee(header: BeaconBlockHeader, ] def get_switchover_epoch(index): return ( - bytes_to_int(hash(validator_memory.earlier_period_data.seed + bytes3(index))[0:8]) % + bytes_to_int(hash(validator_memory.earlier_period_data.seed + int_to_bytes3(index))[0:8]) % PERSISTENT_COMMITTEE_PERIOD ) # Take not-yet-cycled-out validators from earlier committee and already-cycled-in validators from # later committee; return a sorted list of the union of the two, deduplicated return sorted(list(set( - [i for i in earlier_committee if epoch % PERSISTENT_COMMITTEE_PERIOD < get_switchover_epoch(i)] + - [i for i in later_committee if epoch % PERSISTENT_COMMITTEE_PERIOD >= get_switchover_epoch(i)] + [i for i in actual_earlier_committee if epoch % PERSISTENT_COMMITTEE_PERIOD < get_switchover_epoch(i)] + + [i for i in actual_later_committee if epoch % PERSISTENT_COMMITTEE_PERIOD >= get_switchover_epoch(i)] ))) ``` @@ -154,23 +177,23 @@ The verification procedure is as follows: ```python def verify_block_validity_proof(proof: BlockValidityProof, validator_memory: ValidatorMemory) -> bool: - assert proof.shard_parent_block.beacon_chain_ref == hash_tree_root(proof.header) + assert proof.shard_parent_block.beacon_chain_root == hash_tree_root(proof.header) committee = compute_committee(proof.header, validator_memory) # Verify that we have >=50% support - support_balance = sum([c.high_balance for i, c in enumerate(committee) if get_bitfield_bit(proof.shard_bitfield, i) is True]) - total_balance = sum([c.high_balance for i, c in enumerate(committee)] + support_balance = sum([v.high_balance for i, v in enumerate(committee) if get_bitfield_bit(proof.shard_bitfield, i) is True]) + total_balance = sum([v.high_balance for i, v in enumerate(committee)]) assert support_balance * 2 > total_balance # Verify shard attestations group_public_key = bls_aggregate_pubkeys([ - v.pubkey for v, index in enumerate(committee) if - get_bitfield_bit(proof.shard_bitfield, i) is True + v.pubkey for v, index in enumerate(committee) + if get_bitfield_bit(proof.shard_bitfield, index) is True ]) assert bls_verify( pubkey=group_public_key, message_hash=hash_tree_root(shard_parent_block), - signature=shard_aggregate_signature, - domain=get_domain(state, slot_to_epoch(shard_block.slot), DOMAIN_SHARD_ATTESTER) + signature=proof.shard_aggregate_signature, + domain=get_domain(state, slot_to_epoch(shard_block.slot), DOMAIN_SHARD_ATTESTER), ) ``` -The size of this proof is only 200 (header) + 96 (signature) + 16 (bitfield) + 352 (shard block) = 664 bytes. It can be reduced further by replacing `ShardBlock` with `MerklePartial(lambda x: x.beacon_chain_ref, ShardBlock)`, which would cut off ~220 bytes. +The size of this proof is only 200 (header) + 96 (signature) + 16 (bitfield) + 352 (shard block) = 664 bytes. It can be reduced further by replacing `ShardBlock` with `MerklePartial(lambda x: x.beacon_chain_root, ShardBlock)`, which would cut off ~220 bytes. From 02cfbca81f1da76d2eb92c934f9fdd81550d0566 Mon Sep 17 00:00:00 2001 From: Hsiao-Wei Wang Date: Sun, 14 Apr 2019 18:17:43 +1000 Subject: [PATCH 8/9] Remove blanks --- specs/light_client/sync_protocol.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/specs/light_client/sync_protocol.md b/specs/light_client/sync_protocol.md index 3850f077de..d5647f0c50 100644 --- a/specs/light_client/sync_protocol.md +++ b/specs/light_client/sync_protocol.md @@ -125,7 +125,7 @@ def compute_committee(header: BeaconBlockHeader, earlier_start_epoch = get_earlier_start_epoch(header.slot) later_start_epoch = get_later_start_epoch(header.slot) epoch = slot_to_epoch(header.slot) - + committee_count = max( earlier_validator_count // (SHARD_COUNT * TARGET_COMMITTEE_SIZE), later_validator_count // (SHARD_COUNT * TARGET_COMMITTEE_SIZE), @@ -137,7 +137,7 @@ def compute_committee(header: BeaconBlockHeader, SHARD_COUNT * committee_count, validator_memory.shard_id * committee_count + (1 if end else 0), ) - + actual_earlier_committee = maximal_earlier_committee[ 0:get_offset(earlier_validator_count, True) - get_offset(earlier_validator_count, False) ] From 0a1517c9de4ec91a93fbd11015423ffb39d97a82 Mon Sep 17 00:00:00 2001 From: Danny Ryan Date: Thu, 18 Apr 2019 08:56:46 +0800 Subject: [PATCH 9/9] Update specs/light_client/merkle_proofs.md Co-Authored-By: hwwhww --- specs/light_client/merkle_proofs.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/specs/light_client/merkle_proofs.md b/specs/light_client/merkle_proofs.md index 46fa23f828..63c018f2f6 100644 --- a/specs/light_client/merkle_proofs.md +++ b/specs/light_client/merkle_proofs.md @@ -144,7 +144,7 @@ Generating a proof is simply a matter of taking the node of the SSZ hash tree wi Here is the verification function: ```python -def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], proof: List[bytes]) -> bool: +def verify_multi_proof(root: Bytes32, indices: List[int], leaves: List[Bytes32], proof: List[Bytes32]) -> bool: tree = {} for index, leaf in zip(indices, leaves): tree[index] = leaf