Python eth_utils.encode_hex() Examples

The following are 30 code examples of eth_utils.encode_hex(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module eth_utils , or try the search function .
Example #1
Source File: handshaker.py    From trinity with MIT License 6 votes vote down vote up
def validate_base_receipt(remote: NodeAPI,
                          receipt: Union[ETHV63HandshakeReceipt, ETHHandshakeReceipt],
                          handshake_params: Union[StatusV63Payload, StatusPayload]) -> None:
    if receipt.handshake_params.network_id != handshake_params.network_id:
        raise WrongNetworkFailure(
            f"{remote} network "
            f"({receipt.handshake_params.network_id}) does not match ours "
            f"({handshake_params.network_id}), disconnecting"
        )

    if receipt.handshake_params.genesis_hash != handshake_params.genesis_hash:
        raise WrongGenesisFailure(
            f"{remote} genesis "
            f"({encode_hex(receipt.handshake_params.genesis_hash)}) does "
            f"not match ours ({encode_hex(handshake_params.genesis_hash)}), "
            f"disconnecting"
        ) 
Example #2
Source File: sloader.py    From shadowlands with MIT License 6 votes vote down vote up
def package(self, eth_address):
        try:
            try: 
                package = self.functions.packages(eth_address).call()
            except NameNotFound:
                # try tacking an .eth on to the address
                package = self.functions.packages(eth_address + '.eth').call()
        
            uri = package[1]
            checksum = encode_hex(package[0])
        except (ValidationError, NameNotFound):
            raise DappNotFound

        if uri == '' or checksum == '0000000000000000000000000000000000000000000000000000000000000000':
            raise DappNotFound

        return uri, checksum.replace('0x','') 
Example #3
Source File: chain.py    From trinity with MIT License 6 votes vote down vote up
def _get_state_by_root(
        db: DatabaseAPI, state_root: Hash32, state_class: Type[BeaconState]
    ) -> BeaconState:
        """
        Return the requested beacon state as specified by state hash.

        Raises StateNotFound if it is not present in the db.
        """
        # TODO: validate_state_root
        if state_root in state_cache and state_root in db:
            return state_cache[state_root]

        try:
            state_ssz = db[state_root]
        except KeyError:
            raise StateNotFound(f"No state with root {encode_hex(state_root)} found")

        state = ssz.decode(state_ssz, state_class)
        state_cache[state] = state
        return state 
Example #4
Source File: run_beacon_nodes.py    From trinity with MIT License 6 votes vote down vote up
def cmd(self) -> str:
        _cmds = [
            "trinity-beacon",
            f"--port={self.port}",
            f"--trinity-root-dir={self.root_dir}",
            f"--beacon-nodekey={remove_0x_prefix(encode_hex(self.node_privkey.to_bytes()))}",
            f"--preferred_nodes={','.join(str(node.maddr) for node in self.preferred_nodes)}",
            f"--http-port={self.http_port}",
            "--enable-http",
            "--enable-metrics",
            "--enable-api",
            f"--api-port={self.api_port}",
            f"--metrics-port={self.metrics_port}",
            "--disable-discovery",
            "-l debug",
            "interop",
            f"--validators={','.join(str(v) for v in self.validators)}",
            f"--start-time={self.start_time}",
            "--wipedb",
        ]
        _cmd = " ".join(_cmds)
        return _cmd 
Example #5
Source File: deposit_helpers.py    From trinity with MIT License 6 votes vote down vote up
def validate_deposit_proof(
    state: BeaconState, deposit: Deposit, deposit_contract_tree_depth: int
) -> None:
    """
    Validate if deposit branch proof is valid.
    """
    is_valid_proof = verify_merkle_branch(
        leaf=deposit.data.hash_tree_root,
        proof=deposit.proof,
        depth=deposit_contract_tree_depth + 1,
        index=state.eth1_deposit_index,
        root=state.eth1_data.deposit_root,
    )
    if not is_valid_proof:
        raise ValidationError(
            f"deposit.proof ({list(map(encode_hex, deposit.proof))}) is invalid against "
            f"leaf={encode_hex(deposit.data.hash_tree_root)}, "
            f"deposit_contract_tree_depth={deposit_contract_tree_depth}, "
            f"deposit.index (via state) = {state.eth1_deposit_index} "
            f"state.eth1_data.deposit_root={state.eth1_data.deposit_root.hex()}"
        ) 
Example #6
Source File: database.py    From raiden-services with MIT License 6 votes vote down vote up
def upsert_channel(self, channel: Channel) -> None:
        values = [
            to_checksum_address(channel.token_network_address),
            hex256(channel.identifier),
            to_checksum_address(channel.participant1),
            to_checksum_address(channel.participant2),
            hex256(channel.settle_timeout),
            channel.state,
            hex256(channel.closing_block) if channel.closing_block else None,
            channel.closing_participant,
            encode_hex(channel.monitor_tx_hash) if channel.monitor_tx_hash else None,
            encode_hex(channel.claim_tx_hash) if channel.claim_tx_hash else None,
        ]
        if channel.update_status:
            values += [
                to_checksum_address(channel.update_status.update_sender_address),
                hex256(channel.update_status.nonce),
            ]
        else:
            values += [None, None]

        upsert_sql = "INSERT OR REPLACE INTO channel VALUES ({})".format(
            ", ".join("?" * len(values))
        )
        self.conn.execute(upsert_sql, values) 
Example #7
Source File: beacon_node.py    From trinity with MIT License 6 votes vote down vote up
def _get_attestation_from_beacon_node(
    session: Session,
    url: str,
    public_key: BLSPubkey,
    slot: Slot,
    committee_index: CommitteeIndex,
) -> Optional[Attestation]:
    attestation_response = await _get_json(
        session,
        url,
        {
            "validator_pubkey": encode_hex(public_key),
            "slot": slot,
            "committee_index": committee_index,
        },
    )
    try:
        return from_formatted_dict(attestation_response, Attestation)
    except Exception as e:
        logger.exception(e)
        return None 
Example #8
Source File: mint_tokens.py    From raiden-contracts with MIT License 6 votes vote down vote up
def main(rpc_url: URI, private_key: Path, token_address: ChecksumAddress, amount: int) -> None:
    web3 = Web3(HTTPProvider(rpc_url))
    privkey = get_private_key(private_key)
    assert privkey is not None
    owner = private_key_to_address(privkey)
    web3.middleware_onion.add(construct_sign_and_send_raw_middleware(privkey))
    token_code = web3.eth.getCode(token_address, "latest")
    assert token_code != HexBytes("")
    token_contract = ContractManager(contracts_precompiled_path()).get_contract(
        CONTRACT_CUSTOM_TOKEN
    )
    token_proxy = web3.eth.contract(address=token_address, abi=token_contract["abi"])
    tx_hash = token_proxy.functions.mint(amount).transact({"from": owner})
    print(f"Minting tokens for address {owner}")
    print(f"Transaction hash {encode_hex(tx_hash)}")
    balance = token_proxy.functions.balanceOf(owner).call()
    print(f"Balance of {owner}: {balance}") 
Example #9
Source File: test_matrix.py    From raiden-services with MIT License 6 votes vote down vote up
def request_monitoring_message(token_network, get_accounts, get_private_key) -> RequestMonitoring:
    c1, c2 = get_accounts(2)

    balance_proof_c2 = HashedBalanceProof(
        channel_identifier=ChannelID(1),
        token_network_address=TokenNetworkAddress(to_canonical_address(token_network.address)),
        chain_id=ChainID(61),
        nonce=Nonce(2),
        additional_hash="0x%064x" % 0,
        transferred_amount=TokenAmount(1),
        locked_amount=TokenAmount(0),
        locksroot=encode_hex(LOCKSROOT_OF_NO_LOCKS),
        priv_key=get_private_key(c2),
    )

    return balance_proof_c2.get_request_monitoring(
        privkey=get_private_key(c1),
        reward_amount=TokenAmount(1),
        monitoring_service_contract_address=MonitoringServiceAddress(bytes([11] * 20)),
    ) 
Example #10
Source File: admin.py    From trinity with MIT License 6 votes vote down vote up
def _generate_protocol_info(
            self,
            protocols: Capabilities) -> Dict[str, RpcProtocolResponse]:

        head = await self.chain.coro_get_canonical_head()
        total_difficulty = await self.chain.coro_get_score(head.hash)
        genesis_header = await self.chain.coro_get_canonical_block_header_by_number(
            BlockNumber(GENESIS_BLOCK_NUMBER)
        )
        chain_config = self.trinity_config.get_app_config(Eth1AppConfig).get_chain_config()

        return {
            protocol: {
                'version': f'{protocol}/{version}',
                'difficulty': total_difficulty,
                'genesis': encode_hex(genesis_header.hash),
                'head': encode_hex(head.hash),
                'network': self.trinity_config.network_id,
                'config': generate_chain_config(chain_config)
            }
            for protocol, version in protocols
        } 
Example #11
Source File: console.py    From trinity with MIT License 6 votes vote down vote up
def get_beacon_shell_context(database_dir: Path,
                             trinity_config: TrinityConfig) -> Iterator[Dict[str, Any]]:
    app_config = trinity_config.get_app_config(BeaconAppConfig)
    ipc_path = trinity_config.database_ipc_path
    trinity_already_running = ipc_path.exists()

    with _get_base_db(database_dir, ipc_path) as db:
        chain_config = app_config.get_chain_config()
        chaindb = BeaconChainDB(db)
        chain = chain_config.beacon_chain_class(
            chaindb,
        )

        head = chaindb.get_canonical_head(BeaconBlock)
        yield {
            'db': db,
            'chaindb': chaindb,
            'trinity_config': trinity_config,
            'chain_config': chain_config,
            'chain': chain,
            'block_number': head.slot,
            'hex_hash': head.hash_tree_root.hex(),
            'state_root_hex': encode_hex(head.state_root),
            'trinity_already_running': trinity_already_running
        } 
Example #12
Source File: genesis.py    From trinity with MIT License 6 votes vote down vote up
def update_genesis_config_with_time(
    config: Dict[str, Any], genesis_time: Timestamp
) -> Dict[str, Any]:
    config_profile = config["profile"]
    eth2_config = _get_eth2_config(config_profile)
    override_lengths(eth2_config)

    existing_state = from_formatted_dict(config["genesis_state"], BeaconState)

    genesis_state = existing_state.set("genesis_time", genesis_time)

    updates = {
        "genesis_state_root": encode_hex(genesis_state.hash_tree_root),
        "genesis_state": to_formatted_dict(genesis_state),
    }
    return {**config, **updates} 
Example #13
Source File: chain.py    From trinity with MIT License 5 votes vote down vote up
def _get_slot_by_root(db: DatabaseAPI, block_root: Root) -> Slot:
        validate_word(block_root, title="block root")
        try:
            encoded_slot = db[SchemaV1.make_block_root_to_slot_lookup_key(block_root)]
        except KeyError:
            raise BlockNotFound(
                "No block with root {0} found".format(encode_hex(block_root))
            )
        return Slot(ssz.decode(encoded_slot, sedes=ssz.sedes.uint64)) 
Example #14
Source File: key_store.py    From trinity with MIT License 5 votes vote down vote up
def _store_key_pairs(self) -> None:
        for public_key, private_key in self._key_pairs.items():
            if self._is_persisted(public_key):
                continue
            password = self._password_provider(public_key)
            private_key_bytes = _serialize_private_key(private_key)
            key_file_json = eth_keyfile.create_keyfile_json(private_key_bytes, password)
            key_file_json["public_key"] = encode_hex(public_key)
            self._store_key_file(key_file_json) 
Example #15
Source File: block_validation.py    From trinity with MIT License 5 votes vote down vote up
def validate_block_parent_root(state: BeaconState, block: BaseBeaconBlock) -> None:
    expected_root = state.latest_block_header.hash_tree_root
    parent_root = block.parent_root
    if parent_root != expected_root:
        raise ValidationError(
            f"block.parent_root ({encode_hex(parent_root)}) is not equal to "
            f"state.latest_block_header.hash_tree_root ({encode_hex(expected_root)}"
        ) 
Example #16
Source File: block_validation.py    From trinity with MIT License 5 votes vote down vote up
def validate_proposer_is_not_slashed(
    state: BeaconState, block_root: Root, config: Eth2Config
) -> None:
    proposer_index = get_beacon_proposer_index(state, config)
    proposer = state.validators[proposer_index]
    if proposer.slashed:
        raise ValidationError(f"Proposer for block {encode_hex(block_root)} is slashed") 
Example #17
Source File: block_validation.py    From trinity with MIT License 5 votes vote down vote up
def validate_proposer_slashing_is_slashable(
    state: BeaconState, proposer: Validator, slots_per_epoch: int
) -> None:
    current_epoch = state.current_epoch(slots_per_epoch)
    is_slashable = proposer.is_slashable(current_epoch)
    if not is_slashable:
        raise ValidationError(
            f"Proposer {encode_hex(proposer.pubkey)} is not slashable in epoch {current_epoch}."
        ) 
Example #18
Source File: epoch_info.py    From trinity with MIT License 5 votes vote down vote up
def __str__(self) -> str:
        return (
            f"({encode_hex(self.previous_justified_checkpoint.root)[0:8]}) "
            f"({encode_hex(self.current_justified_checkpoint.root)[0:8]}) "
            f"({encode_hex(self.finalized_checkpoint.root)[0:8]})"
        ) 
Example #19
Source File: chain.py    From trinity with MIT License 5 votes vote down vote up
def _get_score(
        db: DatabaseAPI, block_root: Root, score_class: Type[BaseScore]
    ) -> BaseScore:
        try:
            encoded_score = db[SchemaV1.make_block_root_to_score_lookup_key(block_root)]
        except KeyError:
            raise BlockNotFound(
                "No block with root {0} found".format(encode_hex(block_root))
            )
        return cast(BaseScore, score_class.deserialize(encoded_score)) 
Example #20
Source File: genesis.py    From trinity with MIT License 5 votes vote down vote up
def generate_genesis_config(
    config_profile: Literal["minimal", "mainnet"], genesis_time: Timestamp
) -> Dict[str, Any]:
    eth2_config = _get_eth2_config(config_profile)
    override_lengths(eth2_config)

    validator_count = eth2_config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT
    validator_key_pairs = create_key_pairs_for(validator_count)
    deposits = create_genesis_deposits_from(
        validator_key_pairs,
        withdrawal_credentials_provider=mk_withdrawal_credentials_from(
            eth2_config.BLS_WITHDRAWAL_PREFIX
        ),
        amount_provider=lambda _public_key: eth2_config.MAX_EFFECTIVE_BALANCE,
    )
    eth1_block_hash = ZERO_HASH32
    eth1_timestamp = eth2_config.MIN_GENESIS_TIME
    initial_state = initialize_beacon_state_from_eth1(
        eth1_block_hash=eth1_block_hash,
        eth1_timestamp=Timestamp(eth1_timestamp),
        deposits=deposits,
        config=eth2_config,
    )

    genesis_state = initial_state.set("genesis_time", genesis_time)

    return {
        "profile": config_profile,
        "eth2_config": eth2_config.to_formatted_dict(),
        "genesis_validator_key_pairs": mk_genesis_key_map(
            validator_key_pairs, genesis_state
        ),
        "genesis_state_root": encode_hex(genesis_state.hash_tree_root),
        "genesis_state": to_formatted_dict(genesis_state),
    } 
Example #21
Source File: initializer.py    From trinity with MIT License 5 votes vote down vote up
def _encode_private_key_as_hex(private_key: int) -> str:
    return encode_hex(private_key.to_bytes(32, "little")) 
Example #22
Source File: beacon_node.py    From trinity with MIT License 5 votes vote down vote up
def _get_duties_from_beacon_node(
    session: Session, url: str, public_keys: Collection[BLSPubkey], epoch: Epoch
) -> Tuple[Dict[str, Any]]:
    return await _get_json(
        session,
        url,
        {
            "validator_pubkeys": ",".join(
                encode_hex(public_key) for public_key in public_keys
            ),
            "epoch": epoch,
        },
    ) 
Example #23
Source File: password_providers.py    From trinity with MIT License 5 votes vote down vote up
def terminal_password_provider(public_key: BLSPubkey) -> bytes:
    return getpass.getpass(
        f"Please enter password for keyfile with public key {encode_hex(public_key)}:"
    ).encode() 
Example #24
Source File: configs.py    From trinity with MIT License 5 votes vote down vote up
def to_formatted_dict(self) -> Iterable[Tuple[str, EncodedConfigTypes]]:
        for field in fields(self):
            if field.type is bytes:
                encoded_value = encode_hex(getattr(self, field.name))
            else:
                encoded_value = getattr(self, field.name)
            yield field.name, encoded_value 
Example #25
Source File: test_etherscan_checkpoint_resolver.py    From trinity with MIT License 5 votes vote down vote up
def test_parse_checkpoint(uri, network_id, min_expected_score):
    checkpoint = parse_checkpoint_uri(uri, network_id)
    assert checkpoint.score >= min_expected_score
    assert is_block_hash(encode_hex(checkpoint.block_hash)) 
Example #26
Source File: component.py    From trinity with MIT License 5 votes vote down vote up
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 
Example #27
Source File: interop_keygen.py    From trinity with MIT License 5 votes vote down vote up
def int_to_hex(n: int, byte_length: int = None) -> str:
    byte_value = int_to_big_endian(n)
    if byte_length:
        byte_value = byte_value.rjust(byte_length, b"\x00")
    return encode_hex(byte_value) 
Example #28
Source File: console.py    From trinity with MIT License 5 votes vote down vote up
def get_eth1_shell_context(database_dir: Path,
                           trinity_config: TrinityConfig) -> Iterator[Dict[str, Any]]:
    app_config = trinity_config.get_app_config(Eth1AppConfig)
    ipc_path = trinity_config.database_ipc_path
    trinity_already_running = ipc_path.exists()

    with _get_base_db(database_dir, ipc_path) as db:
        chaindb = ChainDB(db)
        head = chaindb.get_canonical_head()
        chain_config = app_config.get_chain_config()
        chain = chain_config.full_chain_class(db)

        mining_chain_class = MiningChain.configure(
            __name__=chain_config.full_chain_class.__name__,
            vm_configuration=chain.vm_configuration,
            chain_id=chain.chain_id,
        )
        mining_chain = mining_chain_class(db)
        yield {
            'db': db,
            'chaindb': chaindb,
            'trinity_config': trinity_config,
            'chain_config': chain_config,
            'chain': chain,
            'mining_chain': mining_chain,
            'block_number': head.block_number,
            'hex_hash': head.hex_hash,
            'state_root_hex': encode_hex(head.state_root),
            'trinity_already_running': trinity_already_running,
        } 
Example #29
Source File: interop_keygen.py    From trinity with MIT License 5 votes vote down vote up
def generate_validator_keypairs(validator_count: int) -> Iterable[Dict]:
    for index in range(validator_count):
        privkey = generate_privkey_from_index(index)
        yield {
            "privkey": int_to_hex(privkey),
            "pubkey": encode_hex(bls.sk_to_pk(privkey)),
        } 
Example #30
Source File: beacon_node.py    From trinity with MIT License 5 votes vote down vote up
def _get_block_proposal_from_beacon_node(
    session: Session, url: str, slot: Slot, randao_reveal: BLSSignature
) -> Optional[BeaconBlock]:
    block_proposal_response = await _get_json(
        session, url, {"slot": slot, "randao_reveal": encode_hex(randao_reveal)}
    )
    try:
        return from_formatted_dict(block_proposal_response, BeaconBlock)
    except Exception as e:
        logger.exception(e)
        return None