本文整理汇总了Python中eth_typing.HexStr方法的典型用法代码示例。如果您正苦于以下问题:Python eth_typing.HexStr方法的具体用法?Python eth_typing.HexStr怎么用?Python eth_typing.HexStr使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类eth_typing
的用法示例。
在下文中一共展示了eth_typing.HexStr方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: to_bytes
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_bytes(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> bytes:
if is_boolean(primitive):
return b"\x01" if primitive else b"\x00"
elif isinstance(primitive, bytearray):
return bytes(primitive)
elif isinstance(primitive, bytes):
return primitive
elif is_integer(primitive):
return to_bytes(hexstr=to_hex(primitive))
elif hexstr is not None:
if len(hexstr) % 2:
# type check ignored here because casting an Optional arg to str is not possible
hexstr = "0x0" + remove_0x_prefix(hexstr) # type: ignore
return decode_hex(hexstr)
elif text is not None:
return text.encode("utf-8")
raise TypeError(
"expected a bool, int, byte or bytearray in first arg, or keyword of hexstr or text"
)
示例2: hexstr_if_str
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def hexstr_if_str(
to_type: Callable[..., T], hexstr_or_primitive: Union[bytes, int, str]
) -> T:
"""
Convert to a type, assuming that strings can be only hexstr (not unicode text)
:param to_type function: takes the arguments (primitive, hexstr=hexstr, text=text),
eg~ to_bytes, to_text, to_hex, to_int, etc
:param hexstr_or_primitive bytes, str, int: value to convert
"""
if isinstance(hexstr_or_primitive, str):
if remove_0x_prefix(HexStr(hexstr_or_primitive)) and not is_hexstr(
hexstr_or_primitive
):
raise ValueError(
"when sending a str, it must be a hex string. Got: {0!r}".format(
hexstr_or_primitive
)
)
return to_type(hexstr=hexstr_or_primitive)
else:
return to_type(hexstr_or_primitive)
示例3: to_normalized_address
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_normalized_address(value: AnyStr) -> HexAddress:
"""
Converts an address to its normalized hexadecimal representation.
"""
try:
hex_address = hexstr_if_str(to_hex, value).lower()
except AttributeError:
raise TypeError(
"Value must be any string, instead got type {}".format(type(value))
)
if is_address(hex_address):
return HexAddress(HexStr(hex_address))
else:
raise ValueError(
"Unknown format {}, attempted to normalize to {}".format(value, hex_address)
)
示例4: to_checksum_address
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_checksum_address(value: AnyStr) -> ChecksumAddress:
"""
Makes a checksum address given a supported format.
"""
norm_address = to_normalized_address(value)
address_hash = encode_hex(keccak(text=remove_0x_prefix(HexStr(norm_address))))
checksum_address = add_0x_prefix(
HexStr(
"".join(
(
norm_address[i].upper()
if int(address_hash[i], 16) > 7
else norm_address[i]
)
for i in range(2, 42)
)
)
)
return ChecksumAddress(HexAddress(checksum_address))
示例5: solidityKeccak
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def solidityKeccak(cls, abi_types: List[TypeStr], values: List[Any]) -> bytes:
"""
Executes keccak256 exactly as Solidity does.
Takes list of abi_types as inputs -- `[uint24, int8[], bool]`
and list of corresponding values -- `[20, [-1, 5, 0], True]`
"""
if len(abi_types) != len(values):
raise ValueError(
"Length mismatch between provided abi types and values. Got "
"{0} types and {1} values.".format(len(abi_types), len(values))
)
if isinstance(cls, type):
w3 = None
else:
w3 = cls
normalized_values = map_abi_data([abi_ens_resolver(w3)], abi_types, values)
hex_string = add_0x_prefix(HexStr(''.join(
remove_0x_prefix(hex_encode_abi_type(abi_type, value))
for abi_type, value
in zip(abi_types, normalized_values)
)))
return cls.keccak(hexstr=hex_string)
示例6: test_verify_existent_deployment
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def test_verify_existent_deployment(token_network_registry_contract: Contract) -> None:
""" Test verify_deployed_contracts_in_filesystem() with an existent deployment data
but with a fake web3 that returns a wrong block number for deployment.
"""
web3_mock = Mock()
web3_mock.version.network = 5
web3_mock.eth.getTransactionReceipt = lambda _: {"blockNumber": 0}
verifier = ContractVerifier(web3=web3_mock, contracts_version=ALDERAAN_VERSION)
# The Mock returns a wrong block number, so the comparison fails.
with pytest.raises(RuntimeError):
verifier.verify_deployed_contracts_in_filesystem()
with pytest.raises(RuntimeError):
verifier.verify_deployed_service_contracts_in_filesystem(
token_address=HexAddress(HexStr("0x5Fc523e13fBAc2140F056AD7A96De2cC0C4Cc63A")),
user_deposit_whole_balance_limit=2 ** 256 - 1,
token_network_registry_address=token_network_registry_contract.address,
)
示例7: test_verify_existent_deployment_with_wrong_code
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def test_verify_existent_deployment_with_wrong_code(
token_network_registry_contract: Contract,
) -> None:
""" Test verify_deployed_contracts_in_filesystem() with an existent deployment data
but with a fake web3 that does not return the correct code.
"""
web3_mock = Mock()
web3_mock.version.network = 5
web3_mock.eth.getTransactionReceipt = lambda _: {
"blockNumber": 10711807,
"gasUsed": 555366,
"contractAddress": "0x8Ff327f7ed03cD6Bd5e611E9e404B47d8c9Db81E",
}
verifier = ContractVerifier(web3=web3_mock, contracts_version=ALDERAAN_VERSION)
# The Mock returns a wrong block number, so the comparison fails.
with pytest.raises(RuntimeError):
verifier.verify_deployed_contracts_in_filesystem()
with pytest.raises(RuntimeError):
verifier.verify_deployed_service_contracts_in_filesystem(
token_address=HexAddress(HexStr("0x5Fc523e13fBAc2140F056AD7A96De2cC0C4Cc63A")),
user_deposit_whole_balance_limit=2 ** 256 - 1,
token_network_registry_address=token_network_registry_contract.address,
)
示例8: test_deploy_services_with_controller
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def test_deploy_services_with_controller(
mock_deploy: MagicMock, mock_verify: MagicMock, privkey_file: IO
) -> None:
""" Calling deploy raiden command """
with patch.object(Eth, "getBalance", return_value=1):
runner = CliRunner()
result = runner.invoke(
services,
deploy_services_arguments(
privkey=privkey_file.name,
save_info=None,
service_registry_controller=HexAddress(HexStr("0x" + "1" * 40)),
token_network_registry_address=FAKE_ADDRESS,
),
)
assert result.exception is None
assert result.exit_code == 0
mock_deploy.assert_called_once()
mock_verify.assert_called_once()
示例9: test_user_deposit_deployment_with_wrong_one_to_n_address
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def test_user_deposit_deployment_with_wrong_one_to_n_address() -> None:
""" ContractVerifier.verify_user_deposit_deployment raises on a wrong OneToN address """
token_addr = HexAddress(HexStr("0xDa12Dc74D2d0881749CCd9330ac4f0aecda5686a"))
user_deposit_constructor_arguments = [token_addr, UINT256_MAX]
wrong_one_to_n_address = FAKE_ADDRESS
user_deposit_mock = MagicMock()
mock_token_address = MagicMock()
mock_token_address.call.return_value = token_addr
user_deposit_mock.functions.token.return_value = mock_token_address
with pytest.raises(RuntimeError):
_verify_user_deposit_deployment(
user_deposit=user_deposit_mock,
constructor_arguments=user_deposit_constructor_arguments,
token_address=token_addr,
user_deposit_whole_balance_limit=UINT256_MAX,
one_to_n_address=wrong_one_to_n_address,
monitoring_service_address=HexAddress(
HexStr("0xb7765972d78B6C97bB0a5a6b7529DC1fb64aA287")
),
)
示例10: to_hex
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_hex(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> HexStr:
"""
Auto converts any supported value into its hex representation.
Trims leading zeros, as defined in:
https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding
"""
if hexstr is not None:
return add_0x_prefix(HexStr(hexstr.lower()))
if text is not None:
return encode_hex(text.encode("utf-8"))
if is_boolean(primitive):
return HexStr("0x1") if primitive else HexStr("0x0")
if isinstance(primitive, (bytes, bytearray)):
return encode_hex(primitive)
elif is_string(primitive):
raise TypeError(
"Unsupported type: The primitive argument must be one of: bytes,"
"bytearray, int or bool and not str"
)
if is_integer(primitive):
return HexStr(hex(primitive))
raise TypeError(
"Unsupported type: '{0}'. Must be one of: bool, str, bytes, bytearray"
"or int.".format(repr(type(primitive)))
)
示例11: to_int
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_int(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> int:
"""
Converts value to its integer representation.
Values are converted this way:
* primitive:
* bytes, bytearrays: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '12' => 12
"""
if hexstr is not None:
return int(hexstr, 16)
elif text is not None:
return int(text)
elif isinstance(primitive, (bytes, bytearray)):
return big_endian_to_int(primitive)
elif isinstance(primitive, str):
raise TypeError("Pass in strings with keyword hexstr or text")
elif isinstance(primitive, (int, bool)):
return int(primitive)
else:
raise TypeError(
"Invalid type. Expected one of int/bool/str/bytes/bytearray. Got "
"{0}".format(type(primitive))
)
示例12: to_text
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def to_text(
primitive: Primitives = None, hexstr: HexStr = None, text: str = None
) -> str:
if hexstr is not None:
return to_bytes(hexstr=hexstr).decode("utf-8")
elif text is not None:
return text
elif isinstance(primitive, str):
return to_text(hexstr=primitive)
elif isinstance(primitive, (bytes, bytearray)):
return primitive.decode("utf-8")
elif is_integer(primitive):
byte_encoding = int_to_big_endian(primitive)
return to_text(byte_encoding)
raise TypeError("Expected an int, bytes, bytearray or hexstr.")
示例13: encode_hex
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def encode_hex(value: AnyStr) -> HexStr:
if not is_string(value):
raise TypeError("Value must be an instance of str or unicode")
elif isinstance(value, (bytes, bytearray)):
ascii_bytes = value
else:
ascii_bytes = value.encode("ascii")
binary_hex = binascii.hexlify(ascii_bytes)
return add_0x_prefix(HexStr(binary_hex.decode("ascii")))
示例14: remove_0x_prefix
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def remove_0x_prefix(value: HexStr) -> HexStr:
if is_0x_prefixed(value):
return HexStr(value[2:])
return value
示例15: add_0x_prefix
# 需要导入模块: import eth_typing [as 别名]
# 或者: from eth_typing import HexStr [as 别名]
def add_0x_prefix(value: HexStr) -> HexStr:
if is_0x_prefixed(value):
return value
return HexStr("0x" + value)