本文整理汇总了Python中eth_utils.to_bytes方法的典型用法代码示例。如果您正苦于以下问题:Python eth_utils.to_bytes方法的具体用法?Python eth_utils.to_bytes怎么用?Python eth_utils.to_bytes使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类eth_utils
的用法示例。
在下文中一共展示了eth_utils.to_bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _to_bytes
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def _to_bytes(value: Any, type_str: str = "bytes32") -> bytes:
"""Convert a value to bytes"""
if isinstance(value, bool) or not isinstance(value, (bytes, str, int)):
raise TypeError(f"Cannot convert {type(value).__name__} '{value}' to {type_str}")
value = _to_hex(value)
if type_str == "bytes":
return eth_utils.to_bytes(hexstr=value)
if type_str == "byte":
type_str = "bytes1"
size = int(type_str.strip("bytes"))
if size < 1 or size > 32:
raise ValueError(f"Invalid type: {type_str}")
try:
return int(value, 16).to_bytes(size, "big")
except OverflowError:
raise OverflowError(f"'{value}' exceeds maximum length for {type_str}")
示例2: sign
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def sign(self, key):
'''Sign this transaction with a private key.
A potentially already existing signature would be overridden.
'''
h = blake2b(digest_size=32)
h.update(rlp.encode(self, ThorTransaction.exclude(["Signature"])))
rawhash = h.digest()
if key in (0, "", b"\x00" * 32, "0" * 64):
raise Exception("Zero privkey cannot sign")
if len(key) == 64:
key = to_bytes(hexstr=key) # we need a binary key
pk = keys.PrivateKey(key)
self.Signature = pk.sign_msg_hash(rawhash).to_bytes()
#
# estimate eth gas
#
示例3: test_wait_neighbours
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_wait_neighbours():
proto = MockDiscoveryProtocol([])
node = random_node()
# Schedule a call to proto.recv_neighbours_v4() simulating a neighbours response from the node
# we expect.
neighbours = (random_node(), random_node(), random_node())
neighbours_msg_payload = [
[n.address.to_endpoint() + [n.pubkey.to_bytes()] for n in neighbours],
discovery._get_msg_expiration(),
]
recv_neighbours_coroutine = asyncio.coroutine(
lambda: proto.recv_neighbours_v4(node, neighbours_msg_payload, b"")
)
asyncio.ensure_future(recv_neighbours_coroutine())
received_neighbours = await proto.wait_neighbours(node)
assert neighbours == received_neighbours
# Ensure wait_neighbours() cleaned up after itself.
assert node not in proto.neighbours_callbacks
# If wait_neighbours() times out, we get an empty list of neighbours.
received_neighbours = await proto.wait_neighbours(node)
assert received_neighbours == tuple()
assert node not in proto.neighbours_callbacks
示例4: random_node
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def random_node():
seed = to_bytes(text="".join(random.sample(string.ascii_lowercase, 10)))
priv_key = keys.PrivateKey(keccak(seed))
return kademlia.Node(priv_key.public_key, random_address())
示例5: test_monitor_multiple_contracts_multiple_events
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_monitor_multiple_contracts_multiple_events(self):
"""Test the monitoring of multiple events in multiple smart contracts
"""
deposit_value = to_wei(1, 'ether')
withdraw_value = deposit_value
key = "hello"
value = "world"
self._create_deposit_event()
self._create_withdraw_event()
self._create_claim_event()
listener = EventListener(rpc_provider=self.provider)
tx_hash = self.bank_contract.functions.deposit(). \
transact({'from': self.web3.eth.accounts[0], 'value': deposit_value})
tx_hash = self.bank_contract.functions.withdraw(withdraw_value). \
transact({'from': self.web3.eth.accounts[0]})
tx_hash = self.claim_contract.functions.setClaim(to_bytes(text=key), to_bytes(text=value)). \
transact({'from': self.web3.eth.accounts[0]})
listener.execute()
self.assertEqual(len(bank_deposit_events), 1, "Deposit event fired")
self.assertEqual(len(bank_withdraw_events), 1, "Withdraw event fired")
self.assertEqual(len(claim_events), 1, "Claim event fired")
示例6: test_to_bytes_primitive
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_to_bytes_primitive(val, expected):
assert to_bytes(val) == expected
示例7: test_to_bytes_hexstr
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_to_bytes_hexstr(val, expected):
assert to_bytes(hexstr=val) == expected
示例8: test_to_bytes_text
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_to_bytes_text(val, expected):
assert to_bytes(text=val) == expected
示例9: private_key_to_address
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def private_key_to_address(private_key: PrivateKey) -> ChecksumAddress:
""" Converts a private key to an Ethereum address. """
if isinstance(private_key, str):
private_key_bytes = to_bytes(hexstr=private_key)
else:
private_key_bytes = private_key
pk = PrivateKey(private_key_bytes)
return public_key_to_address(pk.public_key)
示例10: get_blacklisted
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def get_blacklisted(self) -> Tuple[NodeID, ...]:
now = datetime.datetime.utcnow()
# mypy doesn't know about the type of the `query()` function
records = self.session.query(BlacklistRecord).filter( # type: ignore
BlacklistRecord.expires_at > now
)
return tuple(NodeID(to_bytes(hexstr=record.node_id)) for record in records)
#
# Helpers
#
示例11: test_extract_forkid
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_extract_forkid():
enr = ENR.from_repr(
"enr:-Jq4QO5zEyIBU5lSa9iaen0A2xUB5_IVrCi1DbyASTTnLV5RJan6aGPr8kU0p0MYKU5YezZgdSUE"
"-GOBEio6Ultyf1Aog2V0aMrJhGN2AZCDGfCggmlkgnY0gmlwhF4_wLuJc2VjcDI1NmsxoQOt7cA_B_Kg"
"nQ5RmwyA6ji8M1Y0jfINItRGbOOwy7XgbIN0Y3CCdl-DdWRwgnZf")
assert extract_forkid(enr) == ForkID(hash=to_bytes(hexstr='0x63760190'), next=1700000)
示例12: test_generate_eth_cap_enr_field
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def test_generate_eth_cap_enr_field():
base_db = AtomicDB()
ChainDB(base_db).persist_header(ROPSTEN_GENESIS_HEADER)
enr_field = await generate_eth_cap_enr_field(ROPSTEN_VM_CONFIGURATION, AsyncHeaderDB(base_db))
enr = ENRFactory(custom_kv_pairs={enr_field[0]: enr_field[1]})
assert extract_forkid(enr) == ForkID(hash=to_bytes(hexstr='0x30c7ddbc'), next=10)
示例13: priv_to_addr
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def priv_to_addr(x):
if len(x) == 64:
key = to_bytes(hexstr=x) # we need a binary key
return keys.PrivateKey(key).public_key.to_address()
示例14: thor_storage_convert_to_eth_storage
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def thor_storage_convert_to_eth_storage(storage):
def _convert_hash(key): return "0x{}".format(encode_hex(sha3(to_bytes(hexstr=key))))
return {
_convert_hash(v["key"]): v
for _, v in storage.items()
}
示例15: fix_signature
# 需要导入模块: import eth_utils [as 别名]
# 或者: from eth_utils import to_bytes [as 别名]
def fix_signature(provider, signer_address, hash_hex, signature, chain_id = 1) -> str:
valid_v_param_values = [27, 28]
# HACK: There is no consensus on whether the signatureHex string should be
# formatted as v + r + s OR r + s + v, and different clients (even
# different versions of the same client) return the signature params in
# different orders. In order to support all client implementations, we
# parse the signature in both ways, and evaluate if either one is a valid
# signature. r + s + v is the most prevalent format from eth_sign, so we
# attempt this first.
ec_signature = _parse_signature_hex_as_rsv(signature)
if ec_signature["v"] in valid_v_param_values:
signature_as_vrst_hex = (
_convert_ec_signature_to_vrs_hex(ec_signature)
+ _Constants.SignatureType.ETH_SIGN.value.to_bytes(
1, byteorder="big"
).hex()
)
valid = is_valid_signature(
provider, hash_hex, signature_as_vrst_hex, signer_address, chain_id
)
if valid is True:
return signature_as_vrst_hex
ec_signature = _parse_signature_hex_as_vrs(signature)
if ec_signature["v"] in valid_v_param_values:
signature_as_vrst_hex = (
_convert_ec_signature_to_vrs_hex(ec_signature)
+ _Constants.SignatureType.ETH_SIGN.value.to_bytes(
1, byteorder="big"
).hex()
)
valid = is_valid_signature(
provider, hash_hex, signature_as_vrst_hex, signer_address, chain_id
)
if valid is True:
return signature_as_vrst_hex
raise RuntimeError(
"Signature returned from web3 provider is in an unknown format."
+ " Attempted to parse as RSV and as VRS."
)