eth2.0-specs/scripts/build_spec.py

321 lines
11 KiB
Python
Raw Normal View History

2019-05-16 14:36:35 +00:00
import re
from function_puller import (
get_spec,
SpecObject,
)
2019-05-16 14:36:35 +00:00
from argparse import ArgumentParser
from typing import (
Dict,
Optional,
)
2019-05-16 14:36:35 +00:00
2019-05-20 08:50:07 +00:00
PHASE0_IMPORTS = '''from typing import (
2019-07-01 01:44:02 +00:00
Any, Dict, Set, Sequence, Tuple, Optional
2019-05-16 14:36:35 +00:00
)
2019-05-16 19:01:32 +00:00
from dataclasses import (
dataclass,
field,
)
2019-06-05 13:29:26 +00:00
from eth2spec.utils.ssz.ssz_impl import (
2019-05-16 14:36:35 +00:00
hash_tree_root,
signing_root,
)
2019-06-05 13:29:26 +00:00
from eth2spec.utils.ssz.ssz_typing import (
2019-06-27 15:47:48 +00:00
bit, boolean, Container, List, Vector, uint64,
Bytes1, Bytes4, Bytes8, Bytes32, Bytes48, Bytes96, Bitlist, Bitvector,
2019-06-05 13:29:26 +00:00
)
2019-05-30 20:57:18 +00:00
from eth2spec.utils.bls import (
2019-05-16 14:36:35 +00:00
bls_aggregate_pubkeys,
bls_verify,
bls_verify_multiple,
2019-06-30 08:58:04 +00:00
bls_sign,
2019-05-16 14:36:35 +00:00
)
2019-05-16 19:01:32 +00:00
2019-05-16 14:36:35 +00:00
from eth2spec.utils.hash_function import hash
2019-05-18 08:42:04 +00:00
'''
2019-05-20 08:50:07 +00:00
PHASE1_IMPORTS = '''from typing import (
2019-08-07 11:29:24 +00:00
Any, Dict, Optional, Set, Sequence, MutableSequence, Tuple, Union,
2019-05-20 08:50:07 +00:00
)
from dataclasses import (
dataclass,
field,
)
2019-06-05 13:29:26 +00:00
from eth2spec.utils.ssz.ssz_impl import (
2019-05-20 08:50:07 +00:00
hash_tree_root,
signing_root,
2019-06-05 13:29:26 +00:00
is_empty,
)
from eth2spec.utils.ssz.ssz_typing import (
Attestation changes + persistent committee changes (#1294) * Minimal attestation simplification * minor fix * Make the tests pass * Decrease `PLACEHOLDER`, Use `compute_epoch_of_shard_slot` * Fix proposer signature name and use get_seed() to calculate current_shuffling_seed * Fix linter error * Add the WIP `test_is_valid_shard_block` * Add `get_shard_block_attester_committee` * Simplified committee selection * Added some helpers and simplified * Update specs/core/1_shard-data-chains.md * Update 1_shard-data-chains.md * Simplified switchover epochs, changed block structure, changed crosslink structure * Update 1_shard-data-chains.md * Moved balance dependency to proposer selection * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md Co-Authored-By: Danny Ryan <dannyjryan@gmail.com> * Update specs/core/1_shard-data-chains.md * Fixed shard header flattening * Update specs/core/1_shard-data-chains.md * Minor fixes * Update specs/core/1_shard-data-chains.md * Update specs/core/1_shard-data-chains.md Co-Authored-By: Hsiao-Wei Wang <hwwang156@gmail.com> * cleanup testing and lint * return none if not active validators in persistent committee * only allow active validators as shard proposer
2019-07-29 13:47:35 +00:00
uint64, bit, boolean, Container, List, Vector, Bytes, BytesN,
Bytes1, Bytes4, Bytes8, Bytes32, Bytes48, Bytes96, Bitlist, Bitvector,
2019-05-20 08:50:07 +00:00
)
2019-05-30 20:57:18 +00:00
from eth2spec.utils.bls import (
2019-05-20 08:50:07 +00:00
bls_aggregate_pubkeys,
bls_verify,
bls_verify_multiple,
)
from eth2spec.utils.hash_function import hash
'''
2019-05-18 08:42:04 +00:00
SUNDRY_FUNCTIONS = '''
2019-06-20 18:25:22 +00:00
# Monkey patch hash cache
_hash = hash
hash_cache: Dict[bytes, Hash] = {}
2019-06-30 08:58:04 +00:00
def get_eth1_data(distance: uint64) -> Hash:
return hash(distance)
2019-06-20 18:25:22 +00:00
def hash(x: bytes) -> Hash:
if x not in hash_cache:
hash_cache[x] = Hash(_hash(x))
return hash_cache[x]
2019-05-16 14:36:35 +00:00
# Monkey patch validator compute committee code
_compute_committee = compute_committee
2019-06-22 16:12:42 +00:00
committee_cache: Dict[Tuple[Hash, Hash, int, int], Sequence[ValidatorIndex]] = {}
2019-05-16 14:36:35 +00:00
2019-06-22 16:12:42 +00:00
def compute_committee(indices: Sequence[ValidatorIndex], # type: ignore
2019-06-17 21:21:45 +00:00
seed: Hash,
index: int,
2019-06-22 16:12:42 +00:00
count: int) -> Sequence[ValidatorIndex]:
2019-06-20 18:25:22 +00:00
param_hash = (hash(b''.join(index.to_bytes(length=4, byteorder='little') for index in indices)), seed, index, count)
2019-05-16 14:36:35 +00:00
2019-06-17 21:21:45 +00:00
if param_hash not in committee_cache:
2019-06-18 19:50:53 +00:00
committee_cache[param_hash] = _compute_committee(indices, seed, index, count)
2019-06-17 21:21:45 +00:00
return committee_cache[param_hash]
2019-05-16 14:36:35 +00:00
# Access to overwrite spec constants based on configuration
def apply_constants_preset(preset: Dict[str, Any]) -> None:
2019-05-16 14:36:35 +00:00
global_vars = globals()
for k, v in preset.items():
2019-06-30 20:12:02 +00:00
if k.startswith('DOMAIN_'):
global_vars[k] = DomainType(v) # domain types are defined as bytes in the configs
else:
global_vars[k] = v
2019-05-16 14:36:35 +00:00
# Deal with derived constants
global_vars['GENESIS_EPOCH'] = compute_epoch_of_slot(GENESIS_SLOT)
2019-05-16 14:36:35 +00:00
# Initialize SSZ types again, to account for changed lengths
init_SSZ_types()
2019-05-18 08:42:04 +00:00
'''
2019-05-20 08:50:07 +00:00
def strip_comments(raw: str) -> str:
2019-06-30 19:25:58 +00:00
comment_line_regex = re.compile(r'^\s+# ')
lines = raw.split('\n')
out = []
for line in lines:
if not comment_line_regex.match(line):
if ' #' in line:
line = line[:line.index(' #')]
out.append(line)
return '\n'.join(out)
def objects_to_spec(functions: Dict[str, str],
custom_types: Dict[str, str],
constants: Dict[str, str],
ssz_objects: Dict[str, str],
inserts: Dict[str, str],
imports: Dict[str, str],
) -> str:
"""
Given all the objects that constitute a spec, combine them into a single pyfile.
"""
new_type_definitions = (
'\n\n'.join(
[
f"class {key}({value}):\n pass\n"
for key, value in custom_types.items()
]
)
)
2019-05-18 08:42:04 +00:00
functions_spec = '\n\n'.join(functions.values())
2019-06-30 20:12:02 +00:00
for k in list(constants.keys()):
if k.startswith('DOMAIN_'):
constants[k] = f"DomainType(({constants[k]}).to_bytes(length=4, byteorder='little'))"
2019-05-30 20:57:18 +00:00
constants_spec = '\n'.join(map(lambda x: '%s = %s' % (x, constants[x]), constants))
2019-06-05 13:29:26 +00:00
ssz_objects_instantiation_spec = '\n\n'.join(ssz_objects.values())
2019-05-18 08:42:04 +00:00
ssz_objects_reinitialization_spec = (
'def init_SSZ_types() -> None:\n global_vars = globals()\n\n '
+ '\n\n '.join([strip_comments(re.sub(r'(?!\n\n)\n', r'\n ', value[:-1]))
for value in ssz_objects.values()])
2019-06-05 13:29:26 +00:00
+ '\n\n'
+ '\n'.join(map(lambda x: ' global_vars[\'%s\'] = %s' % (x, x), ssz_objects.keys()))
2019-05-18 08:42:04 +00:00
)
2019-05-24 14:51:21 +00:00
spec = (
2019-05-20 08:50:07 +00:00
imports
+ '\n\n' + new_type_definitions
2019-05-20 12:00:54 +00:00
+ '\n\n' + constants_spec
2019-06-05 13:29:26 +00:00
+ '\n\n\n' + ssz_objects_instantiation_spec
+ '\n\n' + functions_spec
2019-05-18 08:42:04 +00:00
+ '\n' + SUNDRY_FUNCTIONS
+ '\n\n' + ssz_objects_reinitialization_spec
+ '\n'
)
2019-05-24 14:51:21 +00:00
# Handle @inserts
for key, value in inserts.items():
spec = re.sub('[ ]*# %s\\n' % key, value, spec)
return spec
2019-05-18 08:42:04 +00:00
2019-06-03 13:14:20 +00:00
def combine_functions(old_functions: Dict[str, str], new_functions: Dict[str, str]) -> Dict[str, str]:
2019-05-18 08:42:04 +00:00
for key, value in new_functions.items():
2019-06-03 13:14:20 +00:00
old_functions[key] = value
return old_functions
2019-05-18 08:42:04 +00:00
def combine_constants(old_constants: Dict[str, str], new_constants: Dict[str, str]) -> Dict[str, str]:
2019-05-18 08:42:04 +00:00
for key, value in new_constants.items():
old_constants[key] = value
return old_constants
2019-05-20 09:17:24 +00:00
ignored_dependencies = [
'bit', 'boolean', 'Vector', 'List', 'Container', 'Hash', 'BLSPubkey', 'BLSSignature', 'Bytes', 'BytesN'
2019-06-30 19:51:10 +00:00
'Bytes1', 'Bytes4', 'Bytes32', 'Bytes48', 'Bytes96', 'Bitlist', 'Bitvector',
'uint8', 'uint16', 'uint32', 'uint64', 'uint128', 'uint256',
'bytes' # to be removed after updating spec doc
]
2019-06-15 21:23:44 +00:00
def dependency_order_ssz_objects(objects: Dict[str, str], custom_types: Dict[str, str]) -> None:
"""
Determines which SSZ Object is depenedent on which other and orders them appropriately
"""
2019-05-20 12:00:54 +00:00
items = list(objects.items())
for key, value in items:
dependencies = []
for line in value.split('\n'):
if not re.match(r'\s+\w+: .+', line):
continue # skip whitespace etc.
line = line[line.index(':') + 1:] # strip of field name
if '#' in line:
line = line[:line.index('#')] # strip of comment
dependencies.extend(re.findall(r'(\w+)', line)) # catch all legible words, potential dependencies
2019-06-20 18:12:17 +00:00
dependencies = filter(lambda x: '_' not in x and x.upper() != x, dependencies) # filter out constants
dependencies = filter(lambda x: x not in ignored_dependencies, dependencies)
dependencies = filter(lambda x: x not in custom_types, dependencies)
2019-05-20 12:00:54 +00:00
for dep in dependencies:
key_list = list(objects.keys())
for item in [dep, key] + key_list[key_list.index(dep)+1:]:
objects[item] = objects.pop(item)
2019-06-15 21:23:44 +00:00
def combine_ssz_objects(old_objects: Dict[str, str], new_objects: Dict[str, str], custom_types) -> Dict[str, str]:
"""
2019-06-03 13:14:20 +00:00
Takes in old spec and new spec ssz objects, combines them,
and returns the newer versions of the objects in dependency order.
"""
2019-05-18 08:42:04 +00:00
for key, value in new_objects.items():
2019-06-05 13:29:26 +00:00
if key in old_objects:
# remove trailing newline
old_objects[key] = old_objects[key]
# remove leading variable name
value = re.sub(r'^class [\w]*\(Container\):\n', '', value)
old_objects[key] = old_objects.get(key, '') + value
2019-06-15 21:23:44 +00:00
dependency_order_ssz_objects(old_objects, custom_types)
2019-05-20 09:17:24 +00:00
return old_objects
2019-05-18 08:42:04 +00:00
2019-05-24 14:51:21 +00:00
# inserts are handeled the same way as functions
combine_inserts = combine_functions
def combine_spec_objects(spec0: SpecObject, spec1: SpecObject) -> SpecObject:
"""
Takes in two spec variants (as tuples of their objects) and combines them using the appropriate combiner function.
"""
functions0, custom_types0, constants0, ssz_objects0, inserts0 = spec0
functions1, custom_types1, constants1, ssz_objects1, inserts1 = spec1
2019-05-26 12:14:48 +00:00
functions = combine_functions(functions0, functions1)
custom_types = combine_constants(custom_types0, custom_types1)
2019-05-26 12:14:48 +00:00
constants = combine_constants(constants0, constants1)
2019-06-15 21:23:44 +00:00
ssz_objects = combine_ssz_objects(ssz_objects0, ssz_objects1, custom_types)
2019-05-26 12:14:48 +00:00
inserts = combine_inserts(inserts0, inserts1)
return functions, custom_types, constants, ssz_objects, inserts
2019-05-26 12:14:48 +00:00
2019-06-30 08:58:04 +00:00
def build_phase0_spec(phase0_sourcefile: str, fork_choice_sourcefile: str,
v_guide_sourcefile: str, outfile: str=None) -> Optional[str]:
2019-06-15 22:42:03 +00:00
phase0_spec = get_spec(phase0_sourcefile)
fork_choice_spec = get_spec(fork_choice_sourcefile)
2019-06-30 08:58:04 +00:00
v_guide = get_spec(v_guide_sourcefile)
spec_objects = phase0_spec
for value in [fork_choice_spec, v_guide]:
spec_objects = combine_spec_objects(spec_objects, value)
spec = objects_to_spec(*spec_objects, PHASE0_IMPORTS)
2019-05-16 14:36:35 +00:00
if outfile is not None:
with open(outfile, 'w') as out:
2019-05-18 08:42:04 +00:00
out.write(spec)
return spec
2019-05-16 14:36:35 +00:00
def build_phase1_spec(phase0_sourcefile: str,
2019-08-11 14:47:23 +00:00
phase1_phase1_shard_misc_source_file: str,
phase1_custody_sourcefile: str,
phase1_shard_sourcefile: str,
2019-06-15 22:42:03 +00:00
fork_choice_sourcefile: str,
outfile: str=None) -> Optional[str]:
phase0_spec = get_spec(phase0_sourcefile)
phase1_custody = get_spec(phase1_custody_sourcefile)
phase1_shard_data = get_spec(phase1_shard_sourcefile)
2019-08-11 16:45:33 +00:00
phase1_shard_misc = get_spec(phase1_phase1_shard_misc_source_file)
2019-06-15 22:42:03 +00:00
fork_choice_spec = get_spec(fork_choice_sourcefile)
2019-05-26 12:14:48 +00:00
spec_objects = phase0_spec
2019-08-11 16:45:33 +00:00
for value in [phase1_custody, phase1_shard_data, phase1_shard_misc, fork_choice_spec]:
2019-05-26 12:14:48 +00:00
spec_objects = combine_spec_objects(spec_objects, value)
2019-06-18 20:16:21 +00:00
spec = objects_to_spec(*spec_objects, PHASE1_IMPORTS)
2019-05-16 14:36:35 +00:00
if outfile is not None:
with open(outfile, 'w') as out:
2019-05-18 08:42:04 +00:00
out.write(spec)
return spec
2019-05-16 14:36:35 +00:00
if __name__ == '__main__':
description = '''
Build the specs from the md docs.
If building phase 0:
2019-08-11 14:47:23 +00:00
1st argument is input 0_beacon-chain.md
2nd argument is input 0_fork-choice.md
3rd argument is input 0_beacon-chain-validator.md
2019-06-30 08:58:04 +00:00
4th argument is output spec.py
2019-05-16 14:36:35 +00:00
If building phase 1:
2019-08-11 14:47:23 +00:00
1st argument is input 0_beacon-chain.md
2019-08-11 16:45:33 +00:00
2nd argument is input 1_custody-game.md
3rd argument is input 1_shard-data-chains.md
4th argument is input 1_shard-chain-misc.md
2019-08-11 14:47:23 +00:00
5th argument is input 0_fork-choice.md
6th argument is output spec.py
2019-05-16 14:36:35 +00:00
'''
parser = ArgumentParser(description=description)
parser.add_argument("-p", "--phase", dest="phase", type=int, default=0, help="Build for phase #")
parser.add_argument(dest="files", help="Input and output files", nargs="+")
args = parser.parse_args()
if args.phase == 0:
2019-06-30 08:58:04 +00:00
if len(args.files) == 4:
build_phase0_spec(*args.files)
else:
2019-06-30 08:58:04 +00:00
print(" Phase 0 requires spec, forkchoice, and v-guide inputs as well as an output file.")
2019-05-16 14:36:35 +00:00
elif args.phase == 1:
2019-08-11 14:47:23 +00:00
if len(args.files) == 6:
2019-05-16 14:36:35 +00:00
build_phase1_spec(*args.files)
else:
2019-08-11 14:47:23 +00:00
print(" Phase 1 requires 6 input files as well as an output file: "
2019-08-11 16:45:33 +00:00
+ "(0_fork-choice.md, 0_beacon-chain.md and 1_custody-game.md, 1_shard-data-chains.md, 1_shard-chain-misc.md output.py)")
2019-05-16 14:36:35 +00:00
else:
print("Invalid phase: {0}".format(args.phase))