Merge branch 'master' into vitalik3

This commit is contained in:
Danny Ryan 2018-10-04 18:55:43 -05:00
commit f003d6b753
No known key found for this signature in database
GPG Key ID: 2765A792E42CE07A
2 changed files with 614 additions and 227 deletions

View File

@ -1,127 +1,120 @@
# Casper+Sharding chain v2.1
# Ethereum 2.0 spec—Casper and sharding
###### tags: `spec`, `eth2.0`, `casper`, `sharding`
###### spec version: 2.2 (October 2018)
## WORK IN PROGRESS!!!!!!!
**NOTICE**: This document is a work-in-progress for researchers and implementers. It reflects recent spec changes and takes precedence over the [Python proof-of-concept implementation](https://github.com/ethereum/beacon_chain).
This is the work-in-progress document describing the specification for the Casper+Sharding (shasper) chain, version 2.1.
### Introduction
In this protocol, there is a central PoS "beacon chain" which stores and manages the current set of active PoS validators. The only mechanism available to become a validator initially is to send a transaction on the existing PoW chain containing 32 ETH. When you do so, as soon as the beacon chain processes that block, you will be queued, and eventually inducted as an active validator until you either voluntarily deregister or you are forcibly deregistered as a penalty for misbehavior.
At the center of Ethereum 2.0 is a system chain called the "beacon chain". The beacon chain stores and manages the set of active proof-of-stake validators. In the initial deployment phases of Ethereum 2.0 the only mechanism to become a validator is to make a fixed-size one-way ETH deposit to a registration contract on the Ethereum 1.0 PoW chain. Induction as a validator happens after registration transaction receipts are processed by the beacon chain and after a queuing process. Deregistration is either voluntary or done forcibly as a penalty for misbehavior.
The primary source of load on the beacon chain is **attestations**. An attestation has a double role:
The primary source of load on the beacon chain are "attestations". Attestations simultaneously attest to a shard block and a corresponding beacon chain block. A sufficient number of attestations for the same shard block create a "crosslink", confirming the shard segment up to that shard block into the beacon chain. Crosslinks also serve as infrastructure for asynchronous cross-shard communication.
1. It attests to some parent block in the beacon chain
2. It attests to a block hash in a shard (a sufficient number of such attestations create a "crosslink", confirming that shard block into the beacon chain).
### Terminology
Every shard (e.g. there might be 1024 shards in total) is itself a PoS chain, and the shard chains are where the transactions and accounts will be stored. The crosslinks serve to "confirm" segments of the shard chains into the beacon chain, and are also the primary way through which the different shards will be able to talk to each other.
Note that one can also consider a simpler "minimal sharding algorithm" where crosslinks are simply hashes of proposed blocks of data that are not themselves chained to each other in any way.
Note: the python code at https://github.com/ethereum/beacon_chain and [an ethresear.ch post](https://ethresear.ch/t/convenience-link-to-full-casper-chain-v2-spec/2332) do not reflect all of the latest changes. If there is a discrepancy, this document is likely to reflect the more recent changes.
### Glossary
* **Validator**—a participant in the Ethereum 2.0 consensus system with the right to produce blocks, attestations, and other consensus objects.
* **Committee**—a statistically representative validator subset, sampled pseudo-randomly.
* **Proposer**—a validator with the right to create a block at a given slot.
* **Attester**—a validator in an attestation committee with the right to attest to a block.
* **Beacon chain**—the central proof-of-state chain of Ethereum 2.0.
* **Shard**—one of the chains on which user transactions take place and contract state is stored.
* **Crosslink**—sufficient signatures from an attestation committee attesting to a given block.
* **Slot**—a period of `SLOT_DURATION` seconds, during which one proposer has the ability to create a block and some attesters have the ability to make attestations
* **Dynasty transition**—a beacon chain state transaction where the validator set may change.
* **Dynasty height**—the number of dynasty transitions that have happened in a given chain since genesis.
* **Cycle**—a span of slots during which all validators get exactly one chance to make an attestation.
* **Finalized**, **justified**—see the [Casper FFG paper](https://arxiv.org/abs/1710.09437). [TODO: flesh out definitions]
* **Validator** - a participant in the Casper/sharding consensus system. You can become one by depositing 32 ETH into the Casper mechanism.
* **Active validator set** - those validators who are currently participating, and which the Casper mechanism looks to produce and attest to blocks, crosslinks and other consensus objects.
* **Committee** - a (pseudo-) randomly sampled subset of the active validator set. When a committee is referred to collectively, as in "this committee attests to X", this is assumed to mean "some subset of that committee that contains enough validators that the protocol recognizes it as representing the committee".
* **Proposer** - the validator that creates a block
* **Attester** - a validator that is part of a committee that needs to sign off on a block.
* **Beacon chain** - the central PoS chain that is the base of the sharding system.
* **Shard chain** - one of the chains on which user transactions take place and account data is stored.
* **Crosslink** - a set of signatures from a committee attesting to a block in a shard chain, which can be included into the beacon chain. Crosslinks are the main means by which the beacon chain "learns about" the updated state of shard chains.
* **Slot** - a period of `SLOT_DURATION` seconds, during which one proposer has the ability to create a block and some attesters have the ability to make attestations
* **Dynasty transition** - a change of the validator set
* **Dynasty** - the number of dynasty transitions that have happened in a given chain since genesis
* **Cycle** - a span of blocks during which all validators get exactly one chance to make an attestation (unless a dynasty transition happens inside of one)
* **Finalized**, **justified** - see Casper FFG finalization here: https://arxiv.org/abs/1710.09437
* **Withdrawal period** - number of slots between a validator exit and the validator balance being withdrawable
* **Genesis time** - the Unix time of the genesis beacon chain block at slot 0
### Constants
* **SHARD_COUNT** - a constant referring to the number of shards. Currently set to 1024.
* **DEPOSIT_SIZE** - 32 ETH, or 32 * 10\*\*18 wei
* **MAX_VALIDATOR_COUNT** - 2<sup>22</sup> = 4194304 # Note: this means that up to ~134 million ETH can stake at the same time
* **GENESIS_TIME** - time of beacon chain startup (slot 0) in seconds since the Unix epoch
* **SLOT_DURATION** - 16 seconds
* **CYCLE_LENGTH** - 64 slots
* **MIN_DYNASTY_LENGTH** - 256 slots
* **MIN_COMMITTEE_SIZE** - 128 (rationale: see recommended minimum 111 here https://vitalik.ca/files/Ithaca201807_Sharding.pdf)
* **SQRT\_E\_DROP\_TIME** - a constant set to reflect the amount of time it will take for the quadratic leak to cut nonparticipating validators' deposits by ~39.4%. Currently set to 2**20 seconds (~12 days).
* **BASE\_REWARD\_QUOTIENT** - 1/this is the per-slot interest rate assuming all validators are participating, assuming total deposits of 1 ETH. Currently set to `2**15 = 32768`, corresponding to ~3.88% annual interest assuming 10 million participating ETH.
* **WITHDRAWAL_PERIOD** - number of slots between a validator exit and the validator slot being withdrawable. Currently set to `2**19 = 524288` slots, or `2**23` seconds ~= 97 days.
* **MAX\_VALIDATOR\_CHANGE\_QUOTIENT** - a maximum of 1/x validators can change during each dynasty. Currently set to 32.
* **PENDING\_LOG\_IN** = 0 (status code)
* **LOGGED\_IN** = 1 (status code)
* **PENDING\_EXIT** = 2 (status code)
* **PENDING\_WITHDRAW** = 3 (status code)
* **PENALIZED** = 128 (status code)
* **WITHDRAWN** = 4 (status code)
| Constant | Value | Unit | Approximation |
| --- | --- | :---: | - |
| `SHARD_COUNT` | 2**10 (= 1,024)| shards |
| `DEPOSIT_SIZE` | 2**5 (= 32) | ETH |
| `MIN_COMMITTEE_SIZE` | 2**7 (= 128) | validators |
| `GENESIS_TIME` | **TBD** | seconds |
| `SLOT_DURATION` | 2**4 (= 16) | seconds |
| `CYCLE_LENGTH` | 2**6 (= 64) | slots | ~17 minutes |
| `MIN_DYNASTY_LENGTH` | 2**8 (= 256) | slots | ~1.1 hours |
| `SQRT_E_DROP_TIME` | 2**16 (= 65,536) | slots | ~12 days |
| `WITHDRAWAL_PERIOD` | 2**19 (= 524,288) | slots | ~97 days |
| `BASE_REWARD_QUOTIENT` | 2**15 (= 32,768) | — |
| `MAX_VALIDATOR_CHURN_QUOTIENT` | 2**5 (= 32) | — |
**Notes**
* The `SQRT_E_DROP_TIME` constant is the amount of time it takes for the quadratic leak to cut deposits of non-participating validators by ~39.4%.
* The `BASE_REWARD_QUOTIENT` constant is the per-slot interest rate assuming all validators are participating, assuming total deposits of 1 ETH. It corresponds to ~3.88% annual interest assuming 10 million participating ETH.
* At most `1/MAX_VALIDATOR_CHURN_QUOTIENT` of the validators can change during each dynasty.
**Status codes**
| Status code | Value |
| - | :-: |
| `PENDING_LOG_IN` | `0` |
| `LOGGED_IN` | `1` |
| `PENDING_EXIT` | `2` |
| `PENDING_WITHDRAW` | `3` |
| `WITHDRAWN` | `4` |
| `PENALIZED` | `128` |
| `ENTRY` | `1` |
| `EXIT` | `2` |
### PoW chain registration contract
The initial deployment phases of Ethereum 2.0 are implemented without consensus changes to the PoW chain. A registration contract is added to the PoW chain to deposit ETH. This contract has a `registration` function which takes the following arguments:
The initial deployment phases of Ethereum 2.0 are implemented without consensus changes to the PoW chain. A registration contract is added to the PoW chain to deposit ETH. This contract has a `registration` function which takes as arguments `pubkey`, `withdrawal_shard`, `withdrawal_address`, `randao_commitment` as defined in a `ValidatorRecord` below. A BLS `proof_of_possession` of types `bytes` is given as a final argument.
1) `pubkey` (bytes)
2) `withdrawal_shard_id` (int)
3) `withdrawal_address` (address)
4) `randao_commitment` (bytes32)
5) `bls_proof_of_possession` (bytes)
The registration contract emits a log with the various arguments for consumption by the beacon chain. It does not do validation, pushing the registration logic to the beacon chain. In particular, the proof of possession (based on the BLS12-381 curve) is not verified by the registration contract.
The registration contract does minimal validation, pushing most of the registration logic to the beacon chain. In particular, the BLS proof of possession (based on the BLS12-381 curve) is not verified by the registration contract.
## Data structures
### Beacon chain blocks
## Data Structures
#### Beacon chain blocks
Beacon chain block structure:
A `BeaconBlock` has the following fields:
```python
fields = {
# Hash of ancestor blocks (32 items, i'th is 2**i'th ancestor or zero bytes)
'ancestor_hashes': ['hash32'],
# Slot number (for the PoS mechanism)
'slot': 'int64',
# Randao commitment reveal
'randao_reveal': 'hash32',
# Attestations
'attestations': [AttestationRecord],
# Reference to PoW chain block
'pow_chain_ref': 'hash32',
# Hash of the active state
'active_state_root': 'hash32',
# Hash of the crystallized state
'crystallized_state_root': 'hash32',
# Logouts, penalties, etc etc
'specials': [SpecialObject]
}
```
A `SpecialObject` looks as follows:
```python
fields = {
'type': 'int8',
'data': ['bytes']
}
```
An `AttestationRecord` looks as follows:
```python
fields = {
{
# Slot number
'slot': 'int64',
# Shard ID
'shard_id': 'int16',
# List of block hashes that this signature is signing over that
# are NOT part of the current chain, in order of oldest to newest
# Proposer RANDAO reveal
'randao_reveal': 'hash32',
# Recent PoW chain reference (block hash)
'pow_chain_reference': 'hash32',
# Skip list of ancestor block hashes (i'th item is 2**i'th ancestor (or zero) for i = 0, ..., 31)
'ancestor_hashes': ['hash32'],
# Active state root
'active_state_root': 'hash32',
# Crystallized state root
'crystallized_state_root': 'hash32',
# Attestations
'attestations': [AttestationRecord],
# Specials (e.g. logouts, penalties)
'specials': [SpecialRecord]
}
```
An `AttestationRecord` has the following fields:
```python
{
# Slot number
'slot': 'int64',
# Shard number
'shard': 'int16',
# Block hashes not part of the current chain, oldest to newest
'oblique_parent_hashes': ['hash32'],
# Block hash in the shard that we are attesting to
# Shard block hash being attested to
'shard_block_hash': 'hash32',
# Who is participating
# Attester participation bitfield (1 bit per attester)
'attester_bitfield': 'bytes',
# Last justified block
# Slot of last justified block
'justified_slot': 'int64',
# Hash of last justified block
'justified_block_hash': 'hash32',
# The actual signature
# BLS aggregate signature
'aggregate_sig': ['int256']
}
```
@ -140,51 +133,66 @@ fields = {
}
```
#### Beacon chain state
The beacon chain state is split into two parts, _active state_ and _crystallized state_.
Here's the `ActiveState`:
A `SpecialRecord` has the following fields:
```python
fields = {
# Attestations that have not yet been processed
'pending_attestations': [AttestationRecord],
# Special objects that have not yet been processed
'pending_specials': [SpecialObject],
# Most recent 2 * CYCLE_LENGTH block hashes, older to newer
'recent_block_hashes': ['hash32']
{
# Kind
'kind': 'int8',
# Data
'data': ['bytes']
}
```
Here's the `CrystallizedState`:
### Beacon chain state
For convenience we define the beacon chain state in two parts: "active state" and "crystallized state".
The `ActiveState` has the following fields:
```python
fields = {
{
# Most recent 2 * CYCLE_LENGTH block hashes, oldest to newest
'recent_block_hashes': ['hash32'],
# Attestations not yet processed
'pending_attestations': [AttestationRecord],
# Specials not yet been processed
'pending_specials': [SpecialRecord]
# Most recent 2 * CYCLE_LENGTH block hashes, older to newer
'recent_block_hashes': ['hash32'],
# RANDAO state
'randao_mix': 'hash32'
}
```
The `CrystallizedState` has the following fields:
```python
{
# Dynasty number
'dynasty': 'int64',
# Dynasty seed (from randomness beacon)
'dynasty_seed': 'hash32',
# Dynasty start
'dynasty_start_slot': 'int64',
# List of validators
'validators': [ValidatorRecord],
# Last CrystallizedState recalculation
'last_state_recalculation': 'int64',
# What active validators are part of the attester set
# at what slot, and in what shard. Starts at slot
# last_state_recalculation - CYCLE_LENGTH
'shard_and_committee_for_slots': [[ShardAndCommittee]],
# The last justified slot
'last_justified_slot': 'int64',
# Number of consecutive justified slots ending at this one
'justified_streak': 'int64',
# The last finalized slot
# Most recent crosslink for each shard
'crosslinks': [CrosslinkRecord],
# Last crystallized state recalculation
'last_state_recalculation_slot': 'int64',
# Last finalized slot
'last_finalized_slot': 'int64',
# The current dynasty
'current_dynasty': 'int64',
# Records about the most recent crosslink `for each shard
'crosslink_records': [CrosslinkRecord],
# Used to select the committees for each shard
'dynasty_seed': 'hash32',
# Start of the current dynasty
'dynasty_start': 'int64',
# Last justified slot
'last_justified_slot': 'int64',
# Number of consecutive justified slots
'justified_streak': 'int64',
# Committee members and their assigned shard, per slot
'shard_and_committee_for_slots': [[ShardAndCommittee]],
# Total deposits penalized in the given withdrawal period
'deposits_penalized_in_period': ['int32'],
# Hash chain of validator set changes (for light clients to easily track deltas)
'validator_set_delta_hash_chain': 'hash32'
# Parameters relevant to hard forks / versioning.
# Should be updated only by hard forks.
'pre_fork_version': 'int32',
@ -193,53 +201,52 @@ fields = {
}
```
Each `ValidatorRecord` is an object containing information about a validator:
A `ValidatorRecord` has the following fields:
```python
fields = {
# The validator's public key
{
# BLS public key
'pubkey': 'int256',
# What shard the validator's balance will be sent to
# after withdrawal
# Withdrawal shard number
'withdrawal_shard': 'int16',
# And what address
# Withdrawal address
'withdrawal_address': 'address',
# The validator's current RANDAO beacon commitment
# RANDAO commitment
'randao_commitment': 'hash32',
# Current balance
# Balance
'balance': 'int128',
# Status (see status codes in constants above)
# Status code
'status': 'int8',
# Slot where this validator leaves
# Slot when validator exited (or 0)
'exit_slot': 'int64'
}
```
A `ShardAndCommittee` object is of the form:
A `CrosslinkRecord` has the following fields:
```python
fields = {
# The shard ID
'shard_id': 'int16',
{
# Dynasty number
'dynasty': 'int64',
# Slot number
'slot': 'int64',
# Beacon chain block hash
'shard_block_hash': 'hash32'
}
```
A `ShardAndCommittee` object has the following fields:
```python
{
# Shard number
'shard': 'int16',
# Validator indices
'committee': ['int24']
}
```
And a `CrosslinkRecord` contains information about the last fully formed crosslink to be submitted into the chain:
```python
fields = {
# What dynasty the crosslink was submitted in
'dynasty': 'int64',
# What slot
'slot': 'int64',
# The block hash
'hash': 'hash32'
}
```
### Beacon chain processing
## Beacon chain processing
The beacon chain is the "main chain" of the PoS system. The beacon chain's main responsibilities are:
@ -253,7 +260,7 @@ For a block on the beacon chain to be processed by a node, four conditions have
* The parent pointed to by the `ancestor_hashes[0]` has already been processed and accepted
* An attestation from the _proposer_ of the block (see later for definition) is included along with the block in the network message object
* The PoW chain block pointed to by the `pow_chain_ref` has already been processed and accepted
* The PoW chain block pointed to by the `pow_chain_reference` has already been processed and accepted
* The node's local clock time is greater than or equal to the minimum timestamp as computed by `GENESIS_TIME + block.slot * SLOT_DURATION`
If these conditions are not met, the client should delay processing the block until the conditions are all satisfied.
@ -277,7 +284,7 @@ Here's an example of its working (green is finalized blocks, yellow is justified
We now define the state transition function. At the high level, the state transition is made up of two parts:
1. The per-block processing, which happens every block, and affects the `ActiveState` only
2. The crystallized state recalculation, which happens only if `block.slot >= last_state_recalculation + CYCLE_LENGTH`, and affects the `CrystallizedState` and `ActiveState`
2. The crystallized state recalculation, which happens only if `block.slot >= last_state_recalculation_slot + CYCLE_LENGTH`, and affects the `CrystallizedState` and `ActiveState`
The crystallized state recalculation generally focuses on changes to the validator set, including adjusting balances and adding and removing validators, as well as processing crosslinks and managing block justification, and the per-block processing generally focuses on verifying aggregate signatures and saving temporary records relating to the in-block activity in the `ActiveState`.
@ -288,29 +295,29 @@ We start off by defining some helper algorithms. First, the function that select
```python
def get_active_validator_indices(validators):
o = []
for i in range(len(validators)):
if validators[i].status == LOGGED_IN:
o.append(i)
return o
return [i for i, v in enumerate(validators) if v.status == LOGGED_IN]
```
Now, a function that shuffles this list:
```python
def shuffle(lst, seed):
assert len(lst) <= 16777216
# entropy is consumed in 3 byte chunks
# rand_max is defined to remove the modulo bias from this entropy source
rand_max = 2**24
assert len(lst) <= rand_max
o = [x for x in lst]
source = seed
i = 0
while i < len(lst):
source = blake(source)
source = hash(source)
for pos in range(0, 30, 3):
m = int.from_bytes(source[pos:pos+3], 'big')
remaining = len(lst) - i
if remaining == 0:
break
rand_max = 16777216 - 16777216 % remaining
rand_max = rand_max - rand_max % remaining
if m < rand_max:
replacement_pos = (m % remaining) + i
o[i], o[replacement_pos] = o[replacement_pos], o[i]
@ -342,10 +349,10 @@ def get_new_shuffling(seed, validators, crosslinking_start_shard):
o = []
for i, slot_indices in enumerate(split(shuffle(active_validators, seed), CYCLE_LENGTH)):
shard_indices = split(slot_indices, committees_per_slot)
shard_id_start = crosslinking_start_shard + \
shard_start = crosslinking_start_shard + \
i * committees_per_slot // slots_per_committee
o.append([ShardAndCommittee(
shard_id = (shard_id_start + j) % SHARD_COUNT,
shard = (shard_start + j) % SHARD_COUNT,
committee = indices
) for j, indices in enumerate(shard_indices)])
return o
@ -359,7 +366,7 @@ We also define two functions for retrieving data from the state:
```python
def get_shards_and_committees_for_slot(crystallized_state, slot):
earliest_slot_in_array = crystallized_state.last_state_recalculation - CYCLE_LENGTH
earliest_slot_in_array = crystallized_state.last_state_recalculation_slot - CYCLE_LENGTH
assert earliest_slot_in_array <= slot < earliest_slot_in_array + CYCLE_LENGTH * 2
return crystallized_state.shard_and_committee_for_slots[slot - earliest_slot_in_array]
@ -369,7 +376,16 @@ def get_block_hash(active_state, curblock, slot):
return active_state.recent_block_hashes[slot - earliest_slot_in_array]
```
`get_block_hash(_, _, h)` should always return the block in the chain at slot `h`, and `get_shards_and_committees_for_slot(_, h)` should not change unless the dynasty changes.
`get_block_hash(_, _, s)` should always return the block in the chain at slot `s`, and `get_shards_and_committees_for_slot(_, s)` should not change unless the dynasty changes.
We define a function to "add a link" to the validator hash chain, used when a validator is added or removed:
```python
def add_validator_set_change_record(crystallized_state, index, pubkey, flag):
crystallized_state.validator_set_delta_hash_chain = \
hash(crystallized_state.validator_set_delta_hash_chain +
bytes1(flag) + bytes3(index) + bytes32(pubkey))
```
Finally, we abstractly define `int_sqrt(n)` for use in reward/penalty calculations as the largest integer `k` such that `k**2 <= n`. Here is one possible implementation, though clients are free to use their own including standard libraries for [integer square root](https://en.wikipedia.org/wiki/Integer_square_root) if available and meet the specification.
@ -400,15 +416,15 @@ def on_startup(initial_validator_entries):
cs = CrystallizedState()
x = get_new_shuffling(bytes([0] * 32), validators, 0)
cs.shard_and_committee_for_slots = x + x
cs.current_dynasty = 1
cs.crosslink_records = [CrosslinkRecord(dynasty=0, slot=0, hash=bytes([0] * 32))
cs.dynasty = 1
cs.crosslinks = [CrosslinkRecord(dynasty=0, slot=0, hash=bytes([0] * 32))
for i in range(SHARD_COUNT)]
# Setup active state
as = ActiveState()
as.recent_block_hashes = [bytes([0] * 32) for _ in range(CYCLE_LENGTH * 2)]
```
The `CrystallizedState()` and `ActiveState()` constructors should initialize all values to zero byes, an empty value or an empty array depending on context. The `add_validator` routine is defined below.
The `CrystallizedState()` and `ActiveState()` constructors should initialize all values to zero bytes, an empty value or an empty array depending on context. The `add_validator` routine is defined below.
### Routine for adding a validator
@ -471,39 +487,41 @@ For each one of these attestations:
* Verify that `slot <= parent.slot` and `slot >= max(parent.slot - CYCLE_LENGTH + 1, 0)`
* Verify that the `justified_slot` and `justified_block_hash` given are in the chain and are equal to or earlier than the `last_justified_slot` in the crystallized state.
* Compute `parent_hashes` = `[get_block_hash(active_state, block, slot - CYCLE_LENGTH + i) for i in range(1, CYCLE_LENGTH - len(oblique_parent_hashes) + 1)] + oblique_parent_hashes` (eg, if `CYCLE_LENGTH = 4`, `slot = 5`, the actual block hashes starting from slot 0 are `Z A B C D E F G H I J`, and `oblique_parent_hashes = [D', E']` then `parent_hashes = [B, C, D' E']`). Note that when *creating* an attestation for a block, the hash of that block itself won't yet be in the `active_state`, so you would need to add it explicitly.
* Let `attestation_indices` be `get_shards_and_committees_for_slot(crystallized_state, slot)[x]`, choosing `x` so that `attestation_indices.shard_id` equals the `shard_id` value provided to find the set of validators that is creating this attestation record.
* Let `attestation_indices` be `get_shards_and_committees_for_slot(crystallized_state, slot)[x]`, choosing `x` so that `attestation_indices.shard` equals the `shard` value provided to find the set of validators that is creating this attestation record.
* Verify that `len(attester_bitfield) == ceil_div8(len(attestation_indices))`, where `ceil_div8 = (x + 7) // 8`. Verify that bits `len(attestation_indices)....` and higher, if present (i.e. `len(attestation_indices)` is not a multiple of 8), are all zero
* Derive a group public key by adding the public keys of all of the attesters in `attestation_indices` for whom the corresponding bit in `attester_bitfield` (the ith bit is `(attester_bitfield[i // 8] >> (7 - (i %8))) % 2`) equals 1
* Let `version = pre_fork_version if slot < fork_slot_number else post_fork_version`.
* Verify that `aggregate_sig` verifies using the group pubkey generated and the serialized form of `AttestationSignedData(version, slot, parent_hashes, shard_id, shard_block_hash, attestation.last_justified_slot)` as the message.
* Verify that `aggregate_sig` verifies using the group pubkey generated and the serialized form of `AttestationSignedData(version, slot, parent_hashes, shard_id, shard_block_hash, justified_slot)` as the message.
Extend the list of `AttestationRecord` objects in the `active_state` with those included in the block, ordering the new additions in the same order as they came in the block. Similarly extend the list of `SpecialObject` objects in the `active_state` with those included in the block.
Extend the list of `AttestationRecord` objects in the `active_state` with those included in the block, ordering the new additions in the same order as they came in the block. Similarly extend the list of `SpecialRecord` objects in the `active_state` with those included in the block.
Verify that the `parent.slot % len(get_shards_and_committees_for_slot(crystallized_state, parent.slot)[0].committee)`'th attester in `get_shards_and_committees_for_slot(crystallized_state, parent.slot)[0]` is part of the first (ie. item 0 in the array) `AttestationRecord` object; this attester can be considered to be the proposer of the parent block. In general, when a block is produced, it is broadcasted at the network layer along with the attestation from its proposer.
Let `proposer_index` be the validator index of the `parent.slot % len(get_shards_and_committees_for_slot(crystallized_state, parent.slot)[0].committee)`'th attester in `get_shards_and_committees_for_slot(crystallized_state, parent.slot)[0]`. Verify that an attestation from this validator is part of the first (ie. item 0 in the array) `AttestationRecord` object; this attester can be considered to be the proposer of the parent block. In general, when a block is produced, it is broadcasted at the network layer along with the attestation from its proposer.
Additionally, verify that `hash(block.randao_reveal) == crystallized_state.validators[proposer_index].randao_commitment`, and set `active_state.randao_mix = xor(active_state.randao_mix, block.randao_reveal)` and `crystallized_state.validators[proposer_index].randao_commitment = block.randao_reveal`.
### State recalculations (every `CYCLE_LENGTH` slots)
Repeat while `slot - last_state_recalculation >= CYCLE_LENGTH`:
Repeat while `slot - last_state_recalculation_slot >= CYCLE_LENGTH`:
#### Adjust justified slots and crosslink status
For all slots `s` in `last_state_recalculation - CYCLE_LENGTH ... last_state_recalculation - 1`:
For all slots `s` in `last_state_recalculation_slot - CYCLE_LENGTH ... last_state_recalculation_slot - 1`:
* Determine the total set of validators that attested to that block at least once
* Determine the total balance of these validators. If this value times three equals or exceeds the total balance of all active validators times two, set `last_justified_slot = max(last_justified_slot, s)` and `justified_streak += 1`. Otherwise, set `justified_streak = 0`
* If `justified_streak >= CYCLE_LENGTH + 1`, set `last_finalized_slot = max(last_finalized_slot, s - CYCLE_LENGTH - 1)`
For all (`shard_id`, `shard_block_hash`) tuples, compute the total deposit size of validators that attested to that block hash for that shard. If this value times three equals or exceeds the total balance of all validators in the committee times two, and the current dynasty exceeds `crosslink_records[shard_id].dynasty`, set `crosslink_records[shard_id] = CrosslinkRecord(dynasty=current_dynasty, slot=block.last_state_recalculation + CYCLE_LENGTH, hash=shard_block_hash)`.
For all (`shard`, `shard_block_hash`) tuples, compute the total deposit size of validators that attested to that block hash for that shard. If this value times three equals or exceeds the total balance of all validators in the committee times two, and the current dynasty exceeds `crosslinks[shard].dynasty`, set `crosslinks[shard] = CrosslinkRecord(dynasty=dynasty, slot=block.last_state_recalculation_slot + CYCLE_LENGTH, hash=shard_block_hash)`.
#### Balance recalculations related to FFG rewards
Let `time_since_finality = block.slot - last_finalized_slot`, and let `B` be the balance of any given validator whose balance we are adjusting, not including any balance changes from this round of state recalculation. Let:
* `total_deposits = sum([v.balance for i, v in enumerate(validators) if i in get_active_validator_indices(validators, current_dynasty)])` and `total_deposits_in_ETH = total_deposits // 10**18`
* `reward_quotient = BASE_REWARD_QUOTIENT * int_sqrt(total_deposits_in_ETH)` (1/this is the per-slot max interest rate)
* `quadratic_penalty_quotient = (SQRT_E_DROP_TIME / SLOT_DURATION)**2` (after D slots, ~D<sup>2</sup>/2 divided by this is the portion lost by offline validators)
* `total_deposits = sum([v.balance for i, v in enumerate(validators) if i in get_active_validator_indices(validators, dynasty)])` and `total_deposits_in_ETH = total_deposits // 10**18`
* `reward_quotient = BASE_REWARD_QUOTIENT * int_sqrt(total_deposits_in_ETH)` (`1/reward_quotient` is the per-slot max interest rate)
* `quadratic_penalty_quotient = SQRT_E_DROP_TIME**2` (after `D` slots about `D*D/2/quadratic_penalty_quotient` is the portion lost by offline validators)
For each slot `S` in the range `last_state_recalculation - CYCLE_LENGTH ... last_state_recalculation - 1`:
For each slot `S` in the range `last_state_recalculation_slot - CYCLE_LENGTH ... last_state_recalculation_slot - 1`:
* Let `total_participated_deposits` be the total balance of validators that voted for the correct hash in slot `S` (ie. the hash that actually is the hash of the block at that slot in the current chain); note that in the normal case, every validator will be in one of the `CYCLE_LENGTH` slots following the slot and so can vote for a hash in slot `S`. If `time_since_finality <= 3 * CYCLE_LENGTH`, then adjust participating and non-participating validators' balances as follows:
* Participating validators gain `B // reward_quotient * (2 * total_participated_deposits - total_deposits) // total_deposits` (note: this may be negative)
@ -516,27 +534,33 @@ Validators with `status == PENALIZED` also lose `B // reward_quotient + B * time
#### Balance recalculations related to crosslink rewards
For each shard S for which a crosslink committee exists in the cycle prior to the most recent cycle (`last_state_recalculation - CYCLE_LENGTH ... last_state_recalculation - 1`), let V be the corresponding validator set. Let `B` be the balance of any given validator whose balance we are adjusting, not including any balance changes from this round of state recalculation. For each S, V do the following:
For each shard `S` for which a crosslink committee exists in the cycle prior to the most recent cycle (`last_state_recalculation_slot - CYCLE_LENGTH ... last_state_recalculation_slot - 1`), let `V` be the corresponding validator set. Let `B` be the balance of any given validator whose balance we are adjusting, not including any balance changes from this round of state recalculation. For each `S`, `V`:
* Let `total_v_deposits` be the total balance of V, and `total_participated_v_deposits` be the total balance of the subset of V that participated (note: it's always true that `total_participated_v_deposits <= total_v_deposits`)
* Let `time_since_last_confirmation` be `block.slot - crosslink_records[S].slot`
* Let `total_v_deposits` be the total balance of `V`
* Let `total_participated_v_deposits` be the total balance of the subset of `V` that participated (note that `total_participated_v_deposits <= total_v_deposits`)
* Let `time_since_last_confirmation` be `block.slot - crosslinks[S].slot`
* Adjust balances as follows:
* If `crosslink_records[S].dynasty == current_dynasty`, no reward adjustments
* Otherwise, participating validators' balances are increased by `B // reward_quotient * (2 * total_participated_v_deposits - total_v_deposits) // total_v_deposits`, and non-participating validators' balances are decreased by `B // reward_quotient + B * time_since_last_confirmation // quadratic_penalty_quotient`
* If `crosslinks[S].dynasty == dynasty`, no reward adjustments
* Otherwise, participating validators' balances are increased by `B // reward_quotient * (2 * total_participated_v_deposits - total_v_deposits) // total_v_deposits`, and the balances of non-participating validators are decreased by `B // reward_quotient + B * time_since_last_confirmation // quadratic_penalty_quotient`
Let `committees` be the set of committees processed and `time_since_last_confirmation(c)` be the value of `time_since_last_confirmation` in that committee. Validators with `status == PENALIZED` lose `B // reward_quotient + B * sum([time_since_last_confirmation(c) for c in committees]) // len(committees) // quadratic_penalty_quotient`.
#### Process penalties, logouts and other special objects
For each `SpecialObject` `obj` in `active_state.pending_specials`:
For each `SpecialRecord` `obj` in `active_state.pending_specials`:
* **[coverts logouts]**: If `obj.type == 0`, interpret `data[0]` as a validator index as an `int32` and `data[1]` as a signature. If `BLSVerify(pubkey=validators[data[0]].pubkey, msg=hash("bye bye"), sig=data[1])`, and `validators[i].status == LOGGED_IN`, set `validators[i].status = PENDING_EXIT` and `validators[i].exit_slot = current_slot`
* **[covers NO\_DBL\_VOTE, NO\_SURROUND, NO\_DBL\_PROPOSE slashing conditions]:** If `obj.type == 1`, interpret `data[0]` as a list of concatenated `int32` values where each value represents an index into `validators`, `data[1]` as the data being signed and `data[2]` as an aggregate signature. Interpret `data[3:6]` similarly. Verify that both signatures are valid, that the two signatures are signing distinct data, and that they are either signing the same slot number, or that one surrounds the other (ie. `source1 < source2 < target2 < target1`). Let `inds` be the list of indices in both signatures; verify that its length is at least 1. For each validator index `v` in `inds`, set their end dynasty to equal the current dynasty + 1, and if its `status` does not equal `PENALIZED`, then (i) set its `exit_slot` to equal the current `slot`, (ii) set its `status` to `PENALIZED`, and (iii) set `crystallized_state.deposits_penalized_in_period[slot // WITHDRAWAL_PERIOD] += validators[v].balance`, extending the array if needed.
* **[covers logouts]**: If `obj.kind == 0`, interpret `data[0]` as a validator index as an `int32` and `data[1]` as a signature. If `BLSVerify(pubkey=validators[data[0]].pubkey, msg=hash("bye bye"), sig=data[1])`, and `validators[i].status == LOGGED_IN`, set `validators[i].status = PENDING_EXIT` and `validators[i].exit_slot = current_slot`
* **[covers `NO_DBL_VOTE`, `NO_SURROUND`, `NO_DBL_PROPOSE` slashing conditions]:** If `obj.kind == 1`, interpret `data[0]` as a list of concatenated `int32` values where each value represents an index into `validators`, `data[1]` as the data being signed and `data[2]` as an aggregate signature. Interpret `data[3:6]` similarly. Verify that both signatures are valid, that the two signatures are signing distinct data, and that they are either signing the same slot number, or that one surrounds the other (ie. `source1 < source2 < target2 < target1`). Let `inds` be the list of indices in both signatures; verify that its length is at least 1. For each validator index `v` in `inds`, set their end dynasty to equal the current dynasty plus 1, and if its `status` does not equal `PENALIZED`, then:
1. Set its `exit_slot` to equal the current `slot`
2. Set its `status` to `PENALIZED`
3. Set `crystallized_state.deposits_penalized_in_period[slot // WITHDRAWAL_PERIOD] += validators[v].balance`, extending the array if needed
4. Run `add_validator_set_change_record(crystallized_state, v, validators[v].pubkey, EXIT)`
#### Finally...
* Set `crystallized_state.last_state_recalculation += CYCLE_LENGTH`
* Remove all attestation records older than slot `crystallized_state.last_state_recalculation`
* Set `crystallized_state.last_state_recalculation_slot += CYCLE_LENGTH`
* Remove all attestation records older than slot `crystallized_state.last_state_recalculation_slot`
* Empty the `active_state.pending_specials` list
* Set `shard_and_committee_for_slots[:CYCLE_LENGTH] = shard_and_committee_for_slots[CYCLE_LENGTH:]`
@ -544,22 +568,22 @@ For each `SpecialObject` `obj` in `active_state.pending_specials`:
A dynasty transition can happen after a state recalculation if all of the following criteria are satisfied:
* `block.slot - crystallized_state.dynasty_start >= MIN_DYNASTY_LENGTH`
* `last_finalized_slot > dynasty_start`
* For every shard `S` in `shard_and_committee_for_slots`, `crosslink_records[S].slot > dynasty_start`
* `block.slot - crystallized_state.dynasty_start_slot >= MIN_DYNASTY_LENGTH`
* `last_finalized_slot > dynasty_start_slot`
* For every shard `S` in `shard_and_committee_for_slots`, `crosslinks[S].slot > dynasty_start_slot`
Then, run the following algorithm to update the validator set:
```python
def change_validators(validators):
# The active validator set
active_validators = get_active_validator_indices(validators, current_dynasty)
active_validators = get_active_validator_indices(validators, dynasty)
# The total size of active deposits
total_deposits = sum([v.balance for i, v in enumerate(validators) if i in active_validators])
# The maximum total wei that can deposit+withdraw
max_allowable_change = max(
DEPOSIT_SIZE * 2,
total_deposits // MAX_VALIDATOR_CHANGE_QUOTIENT
total_deposits // MAX_VALIDATOR_CHURN_QUOTIENT
)
# Go through the list start to end depositing+withdrawing as many as possible
total_changed = 0
@ -567,10 +591,12 @@ def change_validators(validators):
if validators[i].status == PENDING_LOG_IN:
validators[i].status = LOGGED_IN
total_changed += DEPOSIT_SIZE
add_validator_set_change_record(crystallized_state, i, validators[i].pubkey, ENTRY)
if validators[i].status == PENDING_EXIT:
validators[i].status = PENDING_WITHDRAW
validators[i].exit_slot = current_slot
total_changed += validators[i].balance
add_validator_set_change_record(crystallized_state, i, validators[i].pubkey, EXIT)
if total_changed >= max_allowable_change:
break
@ -596,41 +622,54 @@ def change_validators(validators):
Finally:
* Set `last_dynasty_start = crystallized_state.last_state_recalculation`
* Set `crystallized_state.current_dynasty += 1`
* Let `next_start_shard = (shard_and_committee_for_slots[-1][-1].shard_id + 1) % SHARD_COUNT`
* Set `shard_and_committee_for_slots[CYCLE_LENGTH:] = get_new_shuffling(block.ancestor_hashes[0], validators, next_start_shard)`
* Set `last_dynasty_start_slot = crystallized_state.last_state_recalculation_slot`
* Set `crystallized_state.dynasty += 1`
* Let `next_start_shard = (shard_and_committee_for_slots[-1][-1].shard + 1) % SHARD_COUNT`
* Set `shard_and_committee_for_slots[CYCLE_LENGTH:] = get_new_shuffling(active_state.randao_mix, validators, next_start_shard)`
-------
### TODO
Note: this is ~80% complete. The main sections that are missing are:
Note: This spec is ~60% complete.
* Logic for the formats of shard chains, who proposes shard blocks, etc. (in an initial release, if desired we could make crosslinks just be Merkle roots of blobs of data; in any case, one can philosophically view the whole point of the shard chains as being a coordination device for choosing what blobs of data to propose as crosslinks)
* Logic for inducting queued validators from the PoW chain
* Penalties for signing or attesting to non-canonical-chain blocks (update: may not be necessary, see https://ethresear.ch/t/attestation-committee-based-full-pos-chains/2259)
* Per-validator proofs of custody, and associated slashing conditions
* Versioning and upgrades
**Missing**
Slashing conditions may include:
* [ ] Specify how `crystallized_state_root` and `active_state_root` are constructed, including Merklelisation logic for light clients
* [ ] Specify the rules around acceptable values for `pow_chain_reference`
* [ ] Specify the shard chain blocks, blobs, proposers, etc.
* [ ] Specify the rules for forced deregistrations
* [ ] Specify the various assumptions (global clock, networking latency, validator honesty, validator liveness, etc.)
* [ ] Specify (in a separate Vyper file) the registration contract on the PoW chain
* [ ] Specify the bootstrapping logic for the beacon chain genesis (e.g. specify a minimum number validators before the genesis block)
* [ ] Specify the logic for proofs of custody, including slashing conditions
* [ ] Add an appendix about the BLS12-381 curve
* [ ] Add an appendix on gossip networks and the offchain signature aggregation logic
* [ ] Add a glossary (in a separate `glossary.md`) to comprehensively and precisely define all the terms
* [ ] Undergo peer review, security audits and formal verification
**Possible rework/additions**
Casper FFG slot equivocation [done]
Casper FFG surround [done]
Beacon chain proposal equivocation [done]
Shard chain proposal equivocation
Proof of custody secret leak
Proof of custody wrong custody bit
Proof of custody no secret reveal
RANDAO leak
* [ ] Replace the IMD fork choice rule with LMD
* [ ] Merklelise `crystallized_state_root` and `active_state_root` into a single root
* [ ] Replace Blake with a STARK-friendly hash function
* [ ] Get rid of dynasties
* [ ] Reduce the slot duration to 8 seconds
* [ ] Allow for the delayed inclusion of aggregated signatures
* [ ] Use a separate networking-optimised serialisation format for networking
* [ ] Harden RANDAO against orphaned reveals
* [ ] Introduce a RANDAO slashing condition for early leakage
* [ ] Use a separate hash function for the proof of possession
* [ ] Rework the `ShardAndCommittee` data structures
* [ ] Add a double-batched Merkle accumulator for historical beacon chain blocks
* [ ] Allow for deposits larger than 32 ETH, as well as deposit top-ups
* [ ] Add penalties for a deposit below 32 ETH (or some other threshold)
* [ ] Add a `SpecialRecord` to (re)register
* [ ] Rework the document for readability
* [ ] Clearly document the various edge cases, e.g. with committee sizing
# Appendix
## Appendix A - Hash function
The general hash function `hash(x)` in this specification is defined as:
`hash(x) := BLAKE2b-512(x)[0:32]`, where `BLAKE2b-512` (`blake2b512`) algorithm is defined in [RFC 7693](https://tools.ietf.org/html/rfc7693) and input `x` is bytes type.
* `BLAKE2b-512` is the *default* `BLAKE2b` algorithm with 64-byte digest size. To get a 32-byte result, the general hash function output is defined as the leftmost `32` bytes of `BLAKE2b-512` hash output.
* The design rationale is keeping using the default algorithm and avoiding too much dependency on external hash function libraries.
We aim to have a STARK-friendly hash function `hash(x)` for the production launch of the beacon chain. While the standardisation process for a STARK-friendly hash function takes place—led by STARKware, who will produce a detailed report with recommendations—we use `BLAKE2b-512` as a placeholder. Specifically, we set `hash(x) := BLAKE2b-512(x)[0:32]` where the `BLAKE2b-512` algorithm is defined in [RFC 7693](https://tools.ietf.org/html/rfc7693) and the input `x` is of type `bytes`.
## Copyright
Copyright and related rights waived via [CC0](https://creativecommons.org/publicdomain/zero/1.0/).

348
specs/simple-serialize.md Normal file
View File

@ -0,0 +1,348 @@
# [WIP] SimpleSerialize (SSZ) Spec
This is the **work in progress** document to describe `simpleserialize`, the
current selected serialization method for Ethereum 2.0 using the Beacon Chain.
This document specifies the general information for serializing and
deserializing objects and data types.
## ToC
* [About](#about)
* [Terminology](#terminology)
* [Constants](#constants)
* [Overview](#overview)
+ [Serialize/Encode](#serializeencode)
- [uint: 8/16/24/32/64/256](#uint-816243264256)
- [Address](#address)
- [Hash](#hash)
* [Hash32](#hash32)
* [Hash96](#hash96)
* [Hash97](#hash97)
- [Bytes](#bytes)
- [List/Vectors](#listvectors)
- [Container (TODO)](#container)
+ [Deserialize/Decode](#deserializedecode)
- [uint: 8/16/24/32/64/256](#uint-816243264256-1)
- [Address](#address-1)
- [Hash](#hash-1)
* [Hash32](#hash32-1)
* [Hash96](#hash96-1)
* [Hash97](#hash97-1)
- [Bytes](#bytes-1)
- [List/Vectors](#listvectors-1)
- [Container (TODO)](#container-1)
* [Implementations](#implementations)
## About
`SimpleSerialize` was first proposed by Vitalik Buterin as the serialization
protocol for use in the Ethereum 2.0 Beacon Chain.
The core feature of `ssz` is the simplicity of the serialization with low
overhead.
## Terminology
| Term | Definition |
|:-------------|:-----------------------------------------------------------------------------------------------|
| `big` | Big Endian |
| `byte_order` | Specifies [endianness:](https://en.wikipedia.org/wiki/Endianness) Big Endian or Little Endian. |
| `len` | Length/Number of Bytes. |
| `to_bytes` | Convert to bytes. Should take parameters ``size`` and ``byte_order``. |
| `from_bytes` | Convert from bytes to object. Should take ``bytes`` and ``byte_order``. |
| `value` | The value to serialize. |
| `rawbytes` | Raw serialized bytes. |
## Constants
| Constant | Value | Definition |
|:---------------|:-----:|:--------------------------------------------------------------------------------------|
| `LENGTH_BYTES` | 4 | Number of bytes used for the length added before a variable-length serialized object. |
## Overview
### Serialize/Encode
#### uint: 8/16/24/32/64/256
Convert directly to bytes the size of the int. (e.g. ``uint16 = 2 bytes``)
All integers are serialized as **big endian**.
| Check to perform | Code |
|:-----------------------|:----------------------|
| Size is a byte integer | ``int_size % 8 == 0`` |
```python
assert(int_size % 8 == 0)
buffer_size = int_size / 8
return value.to_bytes(buffer_size, 'big')
```
#### Address
The address should already come as a hash/byte format. Ensure that length is
**20**.
| Check to perform | Code |
|:-----------------------|:---------------------|
| Length is correct (20) | ``len(value) == 20`` |
```python
assert( len(value) == 20 )
return value
```
#### Hash
| Hash Type | Usage |
|:---------:|:------------------------------------------------|
| `hash32` | Hash size of ``keccak`` or `blake2b[0.. < 32]`. |
| `hash96` | BLS Public Key Size. |
| `hash97` | BLS Public Key Size with recovery bit. |
| Checks to perform | Code |
|:-----------------------------------|:---------------------|
| Length is correct (32) if `hash32` | ``len(value) == 32`` |
| Length is correct (96) if `hash96` | ``len(value) == 96`` |
| Length is correct (97) if `hash97` | ``len(value) == 97`` |
**Example all together**
```python
if (type(value) == 'hash32'):
assert(len(value) == 32)
elif (type(value) == 'hash96'):
assert(len(value) == 96)
elif (type(value) == 'hash97'):
assert(len(value) == 97)
else:
raise TypeError('Invalid hash type supplied')
return value
```
##### Hash32
Ensure 32 byte length and return the bytes.
```python
assert(len(value) == 32)
return value
```
##### Hash96
Ensure 96 byte length and return the bytes.
```python
assert(len(value) == 96)
return value
```
##### Hash97
Ensure 97 byte length and return the bytes.
```python
assert(len(value) == 97)
return value
```
#### Bytes
For general `byte` type:
1. Get the length/number of bytes; Encode into a `4-byte` integer.
2. Append the value to the length and return: ``[ length_bytes ] + [
value_bytes ]``
| Check to perform | Code |
|:-------------------------------------|:-----------------------|
| Length of bytes can fit into 4 bytes | ``len(value) < 2**32`` |
```python
assert(len(value) < 2**32)
byte_length = (len(value)).to_bytes(LENGTH_BYTES, 'big')
return byte_length + value
```
#### List/Vectors
| Check to perform | Code |
|:--------------------------------------------|:----------------------------|
| Length of serialized list fits into 4 bytes | ``len(serialized) < 2**32`` |
1. Get the number of raw bytes to serialize: it is ``len(list) * sizeof(element)``.
* Encode that as a `4-byte` **big endian** `uint32`.
2. Append the elements in a packed manner.
* *Note on efficiency*: consider using a container that does not need to iterate over all elements to get its length. For example Python lists, C++ vectors or Rust Vec.
**Example in Python**
```python
serialized_list_string = b''
for item in value:
serialized_list_string += serialize(item)
assert(len(serialized_list_string) < 2**32)
serialized_len = (len(serialized_list_string).to_bytes(LENGTH_BYTES, 'big'))
return serialized_len + serialized_list_string
```
#### Container
```
########################################
TODO
########################################
```
### Deserialize/Decode
The decoding requires knowledge of the type of the item to be decoded. When
performing decoding on an entire serialized string, it also requires knowledge
of the order in which the objects have been serialized.
Note: Each return will provide ``deserialized_object, new_index`` keeping track
of the new index.
At each step, the following checks should be made:
| Check to perform | Check |
|:-------------------------|:-----------------------------------------------------------|
| Ensure sufficient length | ``length(rawbytes) >= current_index + deserialize_length`` |
#### uint: 8/16/24/32/64/256
Convert directly from bytes into integer utilising the number of bytes the same
size as the integer length. (e.g. ``uint16 == 2 bytes``)
All integers are interpreted as **big endian**.
```python
assert(len(rawbytes) >= current_index + int_size)
byte_length = int_size / 8
new_index = current_index + int_size
return int.from_bytes(rawbytes[current_index:current_index+int_size], 'big'), new_index
```
#### Address
Return the 20 bytes.
```python
assert(len(rawbytes) >= current_index + 20)
new_index = current_index + 20
return rawbytes[current_index:current_index+20], new_index
```
#### Hash
##### Hash32
Return the 32 bytes.
```python
assert(len(rawbytes) >= current_index + 32)
new_index = current_index + 32
return rawbytes[current_index:current_index+32], new_index
```
##### Hash96
Return the 96 bytes.
```python
assert(len(rawbytes) >= current_index + 96)
new_index = current_index + 96
return rawbytes[current_index:current_index+96], new_index
```
##### Hash97
Return the 97 bytes.
```python
assert(len(rawbytes) >= current_index + 97)
new_index = current_index + 97
return rawbytes[current_index:current_index+97], new_index
```
#### Bytes
Get the length of the bytes, return the bytes.
| Check to perform | code |
|:--------------------------------------------------|:-------------------------------------------------|
| rawbytes has enough left for length | ``len(rawbytes) > current_index + LENGTH_BYTES`` |
| bytes to return not greater than serialized bytes | ``len(rawbytes) > bytes_end `` |
```python
assert(len(rawbytes) > current_index + LENGTH_BYTES)
bytes_length = int.from_bytes(rawbytes[current_index:current_index + LENGTH_BYTES], 'big')
bytes_start = current_index + LENGTH_BYTES
bytes_end = bytes_start + bytes_length
new_index = bytes_end
assert(len(rawbytes) >= bytes_end)
return rawbytes[bytes_start:bytes_end], new_index
```
#### List/Vectors
Deserialize each object in the list.
1. Get the length of the serialized list.
2. Loop through deserializing each item in the list until you reach the
entire length of the list.
| Check to perform | code |
|:------------------------------------------|:----------------------------------------------------------------|
| rawbytes has enough left for length | ``len(rawbytes) > current_index + LENGTH_BYTES`` |
| list is not greater than serialized bytes | ``len(rawbytes) > current_index + LENGTH_BYTES + total_length`` |
```python
assert(len(rawbytes) > current_index + LENGTH_BYTES)
total_length = int.from_bytes(rawbytes[current_index:current_index + LENGTH_BYTES], 'big')
new_index = current_index + LENGTH_BYTES + total_length
assert(len(rawbytes) >= new_index)
item_index = current_index + LENGTH_BYTES
deserialized_list = []
while item_index < new_index:
object, item_index = deserialize(rawbytes, item_index, item_type)
deserialized_list.append(object)
return deserialized_list, new_index
```
#### Container
```
########################################
TODO
########################################
```
## Implementations
| Language | Implementation | Description |
|:--------:|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------|
| Python | [ https://github.com/ethereum/beacon_chain/blob/master/ssz/ssz.py ](https://github.com/ethereum/beacon_chain/blob/master/ssz/ssz.py) | Beacon chain reference implementation written in Python. |
| Rust | [ https://github.com/sigp/lighthouse/tree/master/ssz ](https://github.com/sigp/lighthouse/tree/master/ssz) | Lighthouse (Rust Ethereum 2.0 Node) maintained SSZ. |
| Nim | [ https://github.com/status-im/nim-beacon-chain/blob/master/beacon_chain/ssz.nim ](https://github.com/status-im/nim-beacon-chain/blob/master/beacon_chain/ssz.nim) | Nim Implementation maintained SSZ. |
| Rust | [ https://github.com/paritytech/shasper/tree/master/util/ssz ](https://github.com/paritytech/shasper/tree/master/util/ssz) | Shasper implementation of SSZ maintained by ParityTech. |