def genesis_time(): return Timestamp(1578096000)
from trinity.extensibility import ( TrioIsolatedComponent, ) from .eth1_monitor import Eth1Monitor # Fake eth1 monitor config # TODO: These configs should be read from a config file, e.g., `eth1_monitor_config.yaml`. DEPOSIT_CONTRACT_ABI = json.loads(deposit_contract_json)["abi"] DEPOSIT_CONTRACT_ADDRESS = b"\x12" * 20 NUM_BLOCKS_CONFIRMED = 100 POLLING_PERIOD = 10 START_BLOCK_NUMBER = BlockNumber(1000) # Configs for fake Eth1DataProvider NUM_DEPOSITS_PER_BLOCK = 0 START_BLOCK_TIMESTAMP = Timestamp(int(time.time()) - 2100) # Around 45 mins ago class Eth1MonitorComponent(TrioIsolatedComponent): name = "Eth1 Monitor" endpoint_name = "eth1-monitor" @property def is_enabled(self) -> bool: return self._boot_info.trinity_config.has_app_config(BeaconAppConfig) @classmethod def configure_parser(cls, arg_parser: ArgumentParser, subparser: _SubParsersAction) -> None: # TODO: For now we use fake eth1 monitor.
) index_to_pubkey = {} keymap = {} # pub -> priv for i, k in enumerate(privkeys): pubkey = bls.privtopub(k) index_to_pubkey[i] = pubkey keymap[pubkey] = k override_lengths(XIAO_LONG_BAO_CONFIG) genesis_state, genesis_block = create_mock_genesis( config=XIAO_LONG_BAO_CONFIG, pubkeys=tuple(keymap.keys()), keymap=keymap, genesis_block_class=SerenityBeaconBlock, genesis_time=Timestamp(int(time.time())), ) class BeaconChainFactory(factory.Factory): class Meta: model = TestnetChain @classmethod def _create( cls, model_class: Type[TestnetChain], *args: Any, **kwargs: Any ) -> BaseBeaconChain: db = kwargs.pop("db", AtomicDB()) chain = model_class.from_genesis( base_db=db,
async def _get_eth1_vote( self, slot: Slot, state: BeaconState, state_machine: BaseBeaconStateMachine) -> Eth1Data: slots_per_eth1_voting_period = state_machine.config.SLOTS_PER_ETH1_VOTING_PERIOD seconds_per_slot = state_machine.config.SECONDS_PER_SLOT eth1_follow_distance = ETH1_FOLLOW_DISTANCE eth1_voting_period_start_timestamp = ( self.genesis_time + (slot - slot % slots_per_eth1_voting_period) * seconds_per_slot) new_eth1_data = await self._request_eth1_data( Timestamp(eth1_voting_period_start_timestamp), eth1_follow_distance, 2 * eth1_follow_distance, ) # Default is the `Eth1Data` at `ETH1_FOLLOW_DISTANCE` default_eth1_data = new_eth1_data[0] # Compute `previous_eth1_distance` which is the distance between current block and # `state.eth1_data`. resp: GetDistanceResponse = await self.event_bus.request( GetDistanceRequest( block_hash=self.starting_eth1_block_hash, eth1_voting_period_start_timestamp=Timestamp( eth1_voting_period_start_timestamp), )) if resp.error is not None: return default_eth1_data previous_eth1_distance = resp.distance # Request all eth1 data within `previous_eth1_distance` all_eth1_data: Tuple[Eth1Data, ...] = () # Copy overlapped eth1 data from `new_eth1_data` if 2 * eth1_follow_distance >= previous_eth1_distance: all_eth1_data = new_eth1_data[:(previous_eth1_distance - eth1_follow_distance)] else: all_eth1_data = new_eth1_data[:] all_eth1_data += await self._request_eth1_data( Timestamp(eth1_voting_period_start_timestamp), 2 * eth1_follow_distance, previous_eth1_distance, ) # Filter out invalid votes voting_period_int_sqroot = integer_squareroot( slots_per_eth1_voting_period) period_tail = slot % slots_per_eth1_voting_period >= voting_period_int_sqroot if period_tail: votes_to_consider = all_eth1_data else: votes_to_consider = new_eth1_data valid_votes: Tuple[Eth1Data, ...] = tuple(vote for vote in state.eth1_data_votes if vote in votes_to_consider) # Vote with most count wins. Otherwise vote for defaute eth1 data. win_vote = max( valid_votes, key=lambda v: ( valid_votes.count(v), -all_eth1_data.index(v), ), # Tiebreak by smallest distance default=default_eth1_data, ) return win_vote
def _get_block_time(self, block_number: BlockNumber) -> Timestamp: return Timestamp( self.start_block_timestamp + (block_number - self.start_block_number) * AVERAGE_BLOCK_TIME )
async def do_run(cls, boot_info: BootInfo, event_bus: EndpointAPI) -> None: trinity_config = boot_info.trinity_config beacon_app_config = trinity_config.get_app_config(BeaconAppConfig) chain_config = beacon_app_config.get_chain_config() base_db = DBClient.connect(trinity_config.database_ipc_path) # TODO: For now we use fake eth1 monitor. # if boot_info.args.eth1client_rpc: # w3: Web3 = Web3.HTTPProvider(boot_info.args.eth1client_rpc) # else: # w3: Web3 = None # TODO: For now we use fake eth1 monitor. So we load validators data from # interop setting and hardcode the deposit data into fake eth1 data provider. chain = chain_config.beacon_chain_class(base_db, chain_config.genesis_config) config = chain.get_state_machine().config key_set = load_yaml_at( Path("eth2/beacon/scripts/quickstart_state/keygen_16_validators.yaml") ) pubkeys, privkeys, withdrawal_credentials = create_keypair_and_mock_withdraw_credentials( config, key_set # type: ignore ) initial_deposits = ( create_mock_deposit_data( config=config, pubkey=pubkey, privkey=privkey, withdrawal_credentials=withdrawal_credential, ) for pubkey, privkey, withdrawal_credential in zip( pubkeys, privkeys, withdrawal_credentials ) ) # Set the timestamp of start block earlier enough so that eth1 monitor # can query up to 2 * `ETH1_FOLLOW_DISTANCE` of blocks in the beginning. start_block_timestamp = ( chain_config.genesis_data.genesis_time - 3 * ETH1_FOLLOW_DISTANCE * AVERAGE_BLOCK_TIME ) with base_db: fake_eth1_data_provider = FakeEth1DataProvider( start_block_number=START_BLOCK_NUMBER, start_block_timestamp=Timestamp(start_block_timestamp), num_deposits_per_block=NUM_DEPOSITS_PER_BLOCK, initial_deposits=tuple(initial_deposits), ) eth1_monitor_service: Service = Eth1Monitor( eth1_data_provider=fake_eth1_data_provider, num_blocks_confirmed=NUM_BLOCKS_CONFIRMED, polling_period=POLLING_PERIOD, start_block_number=BlockNumber(START_BLOCK_NUMBER - 1), event_bus=event_bus, base_db=base_db, ) try: await TrioManager.run_service(eth1_monitor_service) except Exception: await event_bus.broadcast( ShutdownRequest("Eth1 Monitor ended unexpectedly") ) raise
def get_genesis_time() -> Timestamp: return Timestamp(int(time.time()) + genesis_delay)
def create_filled_state( cls, *, genesis_epoch: Epoch, genesis_start_shard: Shard, genesis_slot: Slot, shard_count: int, slots_per_historical_root: int, latest_active_index_roots_length: int, latest_randao_mixes_length: int, latest_slashed_exit_length: int, activated_genesis_validators: Sequence[Validator] = (), genesis_balances: Sequence[Gwei] = () ) -> 'BeaconState': return cls( # Misc slot=genesis_slot, genesis_time=Timestamp(0), fork=Fork( previous_version=(0).to_bytes(4, 'little'), current_version=(0).to_bytes(4, 'little'), epoch=genesis_epoch, ), # Validator registry validator_registry=activated_genesis_validators, validator_balances=genesis_balances, validator_registry_update_epoch=genesis_epoch, # Randomness and committees latest_randao_mixes=(ZERO_HASH32, ) * latest_randao_mixes_length, previous_shuffling_start_shard=genesis_start_shard, current_shuffling_start_shard=genesis_start_shard, previous_shuffling_epoch=genesis_epoch, current_shuffling_epoch=genesis_epoch, previous_shuffling_seed=ZERO_HASH32, current_shuffling_seed=ZERO_HASH32, # Finality previous_epoch_attestations=(), current_epoch_attestations=(), previous_justified_epoch=genesis_epoch, current_justified_epoch=genesis_epoch, previous_justified_root=ZERO_HASH32, current_justified_root=ZERO_HASH32, justification_bitfield=0, finalized_epoch=genesis_epoch, finalized_root=ZERO_HASH32, # Recent state latest_crosslinks=((Crosslink( epoch=genesis_epoch, crosslink_data_root=ZERO_HASH32, ), ) * shard_count), latest_block_roots=(ZERO_HASH32, ) * slots_per_historical_root, latest_state_roots=(ZERO_HASH32, ) * slots_per_historical_root, latest_active_index_roots=(ZERO_HASH32, ) * latest_active_index_roots_length, latest_slashed_balances=(Gwei(0), ) * latest_slashed_exit_length, latest_block_header=get_temporary_block_header( BeaconBlock.create_empty_block(genesis_slot), ), historical_roots=(), # Ethereum 1.0 chain data latest_eth1_data=Eth1Data.create_empty_data(), eth1_data_votes=(), deposit_index=len(activated_genesis_validators), )
from eth.constants import ZERO_HASH32 from eth_typing import BLSPubkey, BLSSignature from eth2.beacon.typing import Epoch, HashTreeRoot, SigningRoot, Timestamp EMPTY_SIGNATURE = BLSSignature(b"\x00" * 96) EMPTY_PUBKEY = BLSPubkey(b"\x00" * 48) GWEI_PER_ETH = 10 ** 9 FAR_FUTURE_EPOCH = Epoch(2 ** 64 - 1) ZERO_SIGNING_ROOT = SigningRoot(ZERO_HASH32) ZERO_HASH_TREE_ROOT = HashTreeRoot(ZERO_HASH32) GENESIS_PARENT_ROOT = ZERO_SIGNING_ROOT ZERO_TIMESTAMP = Timestamp(0) MAX_INDEX_COUNT = 2 ** 40 MAX_RANDOM_BYTE = 2 ** 8 - 1 BASE_REWARDS_PER_EPOCH = 4 DEPOSIT_CONTRACT_TREE_DEPTH = 2 ** 5 SECONDS_PER_DAY = 86400 JUSTIFICATION_BITS_LENGTH = 4
def _genesis_time_from_eth1_timestamp(eth1_timestamp: Timestamp) -> Timestamp: return Timestamp(eth1_timestamp - eth1_timestamp % SECONDS_PER_DAY + 2 * SECONDS_PER_DAY)
def genesis_time(self) -> Timestamp: return Timestamp(self._genesis_time)
def create_filled_state(cls, *, genesis_epoch: EpochNumber, genesis_start_shard: ShardNumber, genesis_slot: SlotNumber, shard_count: int, latest_block_roots_length: int, latest_index_roots_length: int, latest_randao_mixes_length: int, latest_penalized_exit_length: int, activated_genesis_validators: Sequence[ValidatorRecord]=(), genesis_balances: Sequence[Gwei]=()) -> 'BeaconState': return cls( # Misc slot=genesis_slot, genesis_time=Timestamp(0), fork=Fork( previous_version=0, current_version=0, epoch=genesis_epoch, ), # Validator registry validator_registry=activated_genesis_validators, validator_balances=genesis_balances, validator_registry_update_epoch=genesis_epoch, # Randomness and committees latest_randao_mixes=tuple( ZERO_HASH32 for _ in range(latest_randao_mixes_length) ), previous_epoch_start_shard=genesis_start_shard, current_epoch_start_shard=genesis_start_shard, previous_calculation_epoch=genesis_epoch, current_calculation_epoch=genesis_epoch, previous_epoch_seed=ZERO_HASH32, current_epoch_seed=ZERO_HASH32, # Finality previous_justified_epoch=genesis_epoch, justified_epoch=genesis_epoch, justification_bitfield=genesis_slot, finalized_epoch=genesis_epoch, # Recent state latest_crosslinks=tuple( CrosslinkRecord( epoch=genesis_epoch, shard_block_root=ZERO_HASH32, ) for _ in range(shard_count) ), latest_block_roots=tuple(ZERO_HASH32 for _ in range(latest_block_roots_length)), latest_index_roots=tuple(ZERO_HASH32 for _ in range(latest_index_roots_length)), latest_penalized_balances=(Gwei(0),) * latest_penalized_exit_length, latest_attestations=(), batched_block_roots=(), # Ethereum 1.0 chain data latest_eth1_data=Eth1Data.create_empty_data(), eth1_data_votes=(), )
def _genesis_time_from_eth1_timestamp(eth1_timestamp: Timestamp, genesis_delay: int) -> Timestamp: return Timestamp(eth1_timestamp + genesis_delay)