本文整理汇总了Python中eth_utils.encode_hex方法的典型用法代码示例。如果您正苦于以下问题:Python eth_utils.encode_hex方法的具体用法?Python eth_utils.encode_hex怎么用?Python eth_utils.encode_hex使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类eth_utils
的用法示例。
在下文中一共展示了eth_utils.encode_hex方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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}")
示例2: package
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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','')
示例3: upsert_channel
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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)
示例4: request_monitoring_message
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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)),
)
示例5: _generate_protocol_info
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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
}
示例6: validate_base_receipt
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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"
)
示例7: get_beacon_shell_context
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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
}
示例8: _get_attestation_from_beacon_node
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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
示例9: update_genesis_config_with_time
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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}
示例10: validate_deposit_proof
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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()}"
)
示例11: _get_state_by_root
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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
示例12: cmd
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
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
示例13: decode_int
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
def decode_int(s):
return int(encode_hex(s[::-1]), 16) if s else 0
示例14: test_ecdh
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
def test_ecdh(privkey_hex, pubkey_hex, ecdh_expected):
privkey = keys.PrivateKey(decode_hex(privkey_hex))
pubkey = keys.PublicKey(decode_hex(pubkey_hex))
assert ecdh_expected == encode_hex(ecies.ecdh_agree(privkey, pubkey))
# FIXME: Document those values; this test was lifted from pydevp2p:
# https://github.com/ethereum/pydevp2p/blob/e1ef07a782b9369d18a8441c3b9bcf12456e0608/devp2p/tests/test_ecies.py#L31
示例15: default
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import encode_hex [as 别名]
def default(self, obj):
if isinstance(obj, HexBytes):
return obj.hex()
elif isinstance(obj, AttributeDict):
return dict(obj)
elif isinstance(obj, bytes):
return encode_hex(obj)
return super().default(obj)