async def get_local_enr(boot_info: BootInfo, node_db: NodeDBAPI, local_private_key: PrivateKey) -> ENR: minimal_enr = UnsignedENR( sequence_number=1, kv_pairs={ b"id": b"v4", b"secp256k1": local_private_key.public_key.to_compressed_bytes(), b"udp": boot_info.args.discovery_port, }, identity_scheme_registry=default_identity_scheme_registry, ).to_signed_enr(local_private_key.to_bytes()) node_id = minimal_enr.node_id try: base_enr = node_db.get_enr(node_id) except KeyError: logger.info( f"No Node for {encode_hex(node_id)} found, creating new one") return minimal_enr else: if any(base_enr[key] != value for key, value in minimal_enr.items()): logger.debug(f"Updating local ENR") return UnsignedENR( sequence_number=base_enr.sequence_number + 1, kv_pairs=merge(dict(base_enr), dict(minimal_enr)), identity_scheme_registry=default_identity_scheme_registry, ).to_signed_enr(local_private_key.to_bytes()) else: return base_enr
def ecdsa_sign(self, msg_hash: bytes, private_key: PrivateKey) -> Signature: private_key_bytes = private_key.to_bytes() signature_bytes = self.keys.PrivateKey( private_key_bytes).sign_recoverable( msg_hash, hasher=None, ) signature = Signature(signature_bytes, backend=self) return signature
def test_enr_signing(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) signature = V4IdentityScheme.create_enr_signature(unsigned_enr, private_key.to_bytes()) message_hash = keccak(unsigned_enr.get_signing_message()) assert private_key.public_key.verify_msg_hash(message_hash, NonRecoverableSignature(signature))
def test_enr_node_id(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) node_id = V4IdentityScheme.extract_node_id(enr) assert node_id == keccak(private_key.public_key.to_bytes())
def test_enr_public_key(): private_key = PrivateKey(b"\x11" * 32) public_key = private_key.public_key.to_compressed_bytes() unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": public_key, b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) assert V4IdentityScheme.extract_public_key(unsigned_enr) == public_key assert V4IdentityScheme.extract_public_key(enr) == public_key
def _resolve_node_key(trinity_config: TrinityConfig, nodekey_seed: Optional[str]) -> PrivateKey: if nodekey_seed: private_key_bytes = hashlib.sha256(nodekey_seed.encode()).digest() nodekey = PrivateKey(private_key_bytes) trinity_config.nodekey = nodekey return if trinity_config.nodekey is None: nodekey = ecies.generate_privkey() with open(trinity_config.nodekey_path, 'wb') as nodekey_file: nodekey_file.write(nodekey.to_bytes()) trinity_config.nodekey = nodekey
def ecdsa_sign_non_recoverable( self, msg_hash: bytes, private_key: PrivateKey) -> NonRecoverableSignature: private_key_bytes = private_key.to_bytes() der_encoded_signature = self.keys.PrivateKey(private_key_bytes).sign( msg_hash, hasher=None, ) rs = der.two_int_sequence_decoder(der_encoded_signature) signature = NonRecoverableSignature(rs=rs, backend=self) return signature
def test_enr_signature_validation(): private_key = PrivateKey(b"\x11" * 32) unsigned_enr = UnsignedENR(0, { b"id": b"v4", b"secp256k1": private_key.public_key.to_compressed_bytes(), b"key1": b"value1", }) enr = unsigned_enr.to_signed_enr(private_key.to_bytes()) V4IdentityScheme.validate_enr_signature(enr) forged_enr = ENR(enr.sequence_number, dict(enr), b"\x00" * 64) with pytest.raises(ValidationError): V4IdentityScheme.validate_enr_signature(forged_enr)
def init(): if os.path.exists('key'): try: with open('key', 'rb') as f: eth_k = PrivateKey(f.read()) return eth_k except Exception as e: print('55', e) pass eth_k = generate_eth_key() with open('key', 'wb') as f: f.write(eth_k.to_bytes()) return eth_k
def __init__( self, local_node_key: PrivateKey, eth2_config: Eth2Config, chain_config: BeaconChainConfig, database_dir: Path, chain_class: Type[BaseBeaconChain], time_provider: TimeProvider = get_unix_time, ) -> None: self._local_key_pair = create_new_key_pair(local_node_key.to_bytes()) self._eth2_config = eth2_config self._clock = _mk_clock(eth2_config, chain_config.genesis_time, time_provider) self._base_db = LevelDB(db_path=database_dir) self._chain_db = BeaconChainDB(self._base_db, eth2_config) if not is_beacon_database_initialized(self._chain_db): initialize_beacon_database(chain_config, self._chain_db, self._base_db) self._chain = chain_class(self._base_db, eth2_config)
def private_key_to_public_key(self, private_key: PrivateKey) -> PublicKey: public_key_bytes = private_key_to_public_key(private_key.to_bytes()) public_key = PublicKey(public_key_bytes, backend=self) return public_key
def ecdsa_sign(self, msg_hash: bytes, private_key: PrivateKey) -> Signature: signature_vrs = ecdsa_raw_sign(msg_hash, private_key.to_bytes()) signature = Signature(vrs=signature_vrs, backend=self) return signature
def private_key_to_public_key(self, private_key: PrivateKey) -> PublicKey: public_key_bytes = self.keys.PrivateKey( private_key.to_bytes()).public_key.format(compressed=False, )[1:] return PublicKey(public_key_bytes, backend=self)
def __init__( self, local_node_key: PrivateKey, eth2_config: Eth2Config, clock: Clock, chain: BaseBeaconChain, validator_api_port: int, client_identifier: str, p2p_maddr: Multiaddr, preferred_nodes: Collection[Multiaddr], bootstrap_nodes: Collection[Multiaddr], ) -> None: self._local_key_pair = create_new_key_pair(local_node_key.to_bytes()) self._eth2_config = eth2_config self._clock = clock self._chain = chain self._block_pool: Set[SignedBeaconBlock] = set() self._slashable_block_pool: Set[SignedBeaconBlock] = set() # FIXME: can we provide `p2p_maddr` as a default listening interface for `_mk_host`? peer_id = PeerID.from_pubkey(self._local_key_pair.public_key) if "p2p" in p2p_maddr: existing_peer_id = p2p_maddr.value_for_protocol("p2p") existing_p2p_maddr = Multiaddr(f"/p2p/{existing_peer_id}") self.logger.warning( "peer identity derived from local key pair %s overriding given identity %s", peer_id, existing_peer_id, ) p2p_maddr = p2p_maddr.decapsulate(existing_p2p_maddr) self._p2p_maddr = p2p_maddr.encapsulate(Multiaddr(f"/p2p/{peer_id}")) # TODO: persist metadata and handle updates... self._metadata_provider = lambda: MetaData.create() self._peer_updater, self._peer_updates = trio.open_memory_channel[ Tuple[PeerID, Any]](0) self._host = Host( self._local_key_pair, peer_id, self._accept_peer_updates, self._get_status, self._get_finalized_root_by_epoch, self._get_block_by_slot, self._get_block_by_root, self._metadata_provider, self._get_fork_digest, self._eth2_config, ) self._preferred_nodes = preferred_nodes self._bootstrap_nodes = bootstrap_nodes self._sync_notifier, self._sync_requests = trio.open_memory_channel[ SyncRequest](0) self._syncer = _mk_syncer() api_context = Context( client_identifier, eth2_config, self._syncer, self._chain, self._clock, _mk_block_broadcaster(self), ) self.validator_api_port = validator_api_port self._validator_api_server = _mk_validator_api_server( self.validator_api_port, api_context)