本文整理汇总了Python中hexbytes.HexBytes方法的典型用法代码示例。如果您正苦于以下问题:Python hexbytes.HexBytes方法的具体用法?Python hexbytes.HexBytes怎么用?Python hexbytes.HexBytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hexbytes
的用法示例。
在下文中一共展示了hexbytes.HexBytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _reset
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def _reset(self) -> None:
self._accounts.clear()
try:
self._accounts = [Account(i) for i in web3.eth.accounts]
except Exception:
pass
# Check if accounts were manually unlocked and add them
try:
unlocked_accounts = CONFIG.active_network["cmd_settings"]["unlock"]
if not isinstance(unlocked_accounts, list):
unlocked_accounts = [unlocked_accounts]
for address in unlocked_accounts:
if isinstance(address, int):
address = HexBytes(address.to_bytes(20, "big")).hex()
account = Account(address)
if account not in self._accounts:
self._accounts.append(account)
except (ConnectionError, ValueError, KeyError):
pass
if self.default not in self._accounts:
self.default = None
示例2: _to_wei
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def _to_wei(value: WeiInputTypes) -> int:
original = value
if value is None:
return 0
if isinstance(value, bytes):
value = HexBytes(value).hex()
if isinstance(value, float) and "e+" in str(value):
num_str, dec = str(value).split("e+")
num = num_str.split(".") if "." in num_str else [num_str, ""]
return int(num[0] + num[1][: int(dec)] + "0" * (int(dec) - len(num[1])))
if not isinstance(value, str):
return _return_int(original, value)
if value[:2] == "0x":
return int(value, 16)
for unit, dec in UNITS.items():
if " " + unit not in value:
continue
num_str = value.split(" ")[0]
num = num_str.split(".") if "." in num_str else [num_str, ""]
return int(num[0] + num[1][: int(dec)] + "0" * (int(dec) - len(num[1])))
return _return_int(original, value)
示例3: web3_request_side_effect
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def web3_request_side_effect(method, params):
if method == 'eth_gasPrice':
return 20000000000
elif method == 'eth_estimateGas':
return 125000
elif method == 'eth_getTransactionCount':
return 1
elif method == 'net_version':
return 42
elif method == 'eth_blockNumber':
return 8400000
elif method == 'eth_call':
encoded_abi = encode_abi(abi_swaps_types, non_zero_balance_abi_contract)
return encoded_abi.hex()
elif method == 'eth_getFilterLogs':
return [
{
'data': '0xbc2424e1dcdd2e425c555bcea35a54fd27cf540e60f18366e153e3fb7cf4490c',
'transactionHash': HexBytes('0x65320e57b9d18ec08388896b029ad1495beb7a57c547440253a1dde01b4485f1'),
}
]
return None
示例4: add_abi
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def add_abi(self, abi) -> int:
"""
Add ABI array into the decoder collection, in this step the method id is generated from:
sha3(function_name + '(' + param_type1 + ... + param_typeN + ')')
:param abi: Array of dictionaries
:return: Items added
:rtype: int
"""
added = 0
abi_sha3 = sha3(str(abi))
# Check that abi was not processed before
if abi_sha3 not in self.added_abis:
for item in abi:
if item.get('name'):
method_id = self.get_method_id(item)
self.methods[method_id] = item
added += 1
if item.get('type') == 'event':
self.events.add(HexBytes(method_id).hex())
self.added_abis[abi_sha3] = None
return added
示例5: test_reorg_ok
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def test_reorg_ok(self):
# Last block hash haven't changed
block_hash_0 = remove_0x_head(HexBytes('0x000000000000000000000000'))
cache.set('0x0', block_hash_0)
cache.set('block_number', '0x1')
Block.objects.create(block_hash=block_hash_0, block_number=0, timestamp=0)
Daemon.objects.all().update(block_number=0)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
block_hash_1 = remove_0x_head(HexBytes('0x111111111111111111111111'))
cache.set('0x1', block_hash_1)
cache.set('block_number', '0x2')
Block.objects.create(block_hash=block_hash_1, block_number=1, timestamp=0)
Daemon.objects.all().update(block_number=1)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
示例6: test_reorg_happened
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def test_reorg_happened(self):
# Last block hash haven't changed
block_hash_0 = remove_0x_head(HexBytes('0x000000000000000000000000'))
cache.set('0x0', block_hash_0)
cache.set('block_number', '0x1')
Block.objects.create(block_hash=block_hash_0, block_number=0, timestamp=0)
Daemon.objects.all().update(block_number=0)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
# Last block hash changed
block_hash_1 = remove_0x_head(HexBytes('0x111111111111111111111111'))
cache.set('0x1', block_hash_1)
cache.set('block_number', '0x2')
block_hash_reorg = '{:040d}'.format(1313)
Block.objects.create(block_hash=block_hash_reorg, block_number=1, timestamp=0)
Daemon.objects.all().update(block_number=1)
(had_reorg, block_number) = check_reorg(Daemon.get_solo().block_number)
self.assertTrue(had_reorg)
self.assertEqual(block_number, 0)
Block.objects.filter(block_number=1).update(block_hash=block_hash_1, timestamp=0)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
示例7: test_reorg_mined_multiple_blocks_ok
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def test_reorg_mined_multiple_blocks_ok(self):
# Last block hash haven't changed
block_hash_0 = remove_0x_head(HexBytes('0x000000000000000000000000'))
cache.set('0x0', block_hash_0)
cache.set('block_number', '0x1')
Block.objects.create(block_hash=block_hash_0, block_number=0, timestamp=0)
Daemon.objects.all().update(block_number=0)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
# new block number changed more than one unit
block_hash_1 = remove_0x_head(HexBytes('0x111111111111111111111111'))
cache.set('0x1', block_hash_1) # set_mocked_testrpc_block_hash
cache.set('block_number', '0x9')
Block.objects.create(block_hash=block_hash_1, block_number=1, timestamp=0)
Daemon.objects.all().update(block_number=1)
(had_reorg, _) = check_reorg(Daemon.get_solo().block_number)
self.assertFalse(had_reorg)
示例8: test_remove_0x_head
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def test_remove_0x_head(self):
self.assertEqual('b58d5491D17ebF46E9DB7F18CeA7C556AE80d53B',
remove_0x_head('0xb58d5491D17ebF46E9DB7F18CeA7C556AE80d53B'))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53b',
remove_0x_head('0xb58d5491d17ebf46e9db7f18cea7c556ae80d53b'))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53B',
remove_0x_head('0xb58d5491d17ebf46e9db7f18cea7c556ae80d53B'))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53b',
remove_0x_head(HexBytes('0xb58d5491D17ebF46E9DB7F18CeA7C556AE80d53B')))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53b',
remove_0x_head(HexBytes('0xb58d5491d17ebf46e9db7f18cea7c556ae80d53B')))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53b',
remove_0x_head(HexBytes('0xb58d5491d17ebf46e9db7f18cea7c556ae80d53B')))
self.assertEqual('b58d5491d17ebf46e9db7f18cea7c556ae80d53b',
remove_0x_head(HexBytes('b58d5491d17ebf46e9db7f18cea7c556ae80d53B')))
示例9: test_json_encoder
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def test_json_encoder(self):
base_address = 'b58d5491d17ebf46e9db7f18cea7c556ae80d53B'
ipfs_hash_string = 'Qme4GBhwNJharbu83iNEsd5WnUhQYM1rBAgCgsSuFMdjcS'
ipfs_hash_bytes = ipfs_hash_string.encode() # b'...'
json = {'ipfs_hash': ipfs_hash_bytes}
# Simulate string encoding and convert back to dict
encoded_json = loads(dumps(json, cls=JsonBytesEncoder))
self.assertEqual(ipfs_hash_bytes.decode(), encoded_json['ipfs_hash'])
json = {'ipfs_hash': ipfs_hash_string}
# Simulate string encoding and convert back to dict
encoded_json = loads(dumps(json, cls=JsonBytesEncoder))
self.assertEqual(ipfs_hash_string, encoded_json['ipfs_hash'])
hex_bytes_address = HexBytes(base_address)
json = {'address': hex_bytes_address}
encoded_json = loads(dumps(json, cls=JsonBytesEncoder))
self.assertEqual(hex_bytes_address.hex(), encoded_json['address'])
bytes_address = bytes.fromhex(base_address)
json = {'address': bytes_address}
encoded_json = loads(dumps(json, cls=JsonBytesEncoder))
self.assertEqual('0x' + bytes_address.hex(), encoded_json['address'])
示例10: _serialize
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def _serialize(self, mixed):
"""Serializes mixed to JSON."""
if isinstance(mixed, str):
# serialize to validate is JSON
mixed = json.loads(mixed)
elif isinstance(mixed, dict):
# web3 3.x -> 4.x: bytes() is not serializable
# also pandas sometimes returns int64
# first-degree HexBytes and np.int64 check as a final trap
for attr, value in mixed.items():
if isinstance(value, HexBytes):
mixed[attr] = value.hex().lower()
elif isinstance(value, np.int64):
mixed[attr] = int(value)
return json.dumps(mixed)
示例11: has_matching_signatures
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def has_matching_signatures(self) -> bool:
"""
Check that the signatures match the terms of trade.
:return: True if the transaction has been signed by both parties
"""
w3 = Web3()
singable_message = encode_defunct(primitive=self.sender_hash)
result = (
w3.eth.account.recover_message( # pylint: disable=no-member
signable_message=singable_message,
signature=HexBytes(self.sender_signature),
)
== self.sender_addr
)
counterparty_signable_message = encode_defunct(primitive=self.counterparty_hash)
result = (
result
and w3.eth.account.recover_message( # pylint: disable=no-member
signable_message=counterparty_signable_message,
signature=HexBytes(self.counterparty_signature),
)
== self.counterparty_addr
)
return result
示例12: check_successful_tx
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def check_successful_tx(
web3: Web3, txid: HexBytes, timeout: int = 180
) -> Tuple[TxReceipt, TxData]:
"""See if transaction went through (Solidity code did not throw).
:return: Transaction receipt and transaction info
"""
receipt = wait_for_transaction_receipt(web3=web3, txid=txid, timeout=timeout)
if receipt is None:
raise RuntimeError("Could not obtain a transaction receipt.")
txinfo = web3.eth.getTransaction(txid)
if "status" not in receipt:
raise KeyError(
'A transaction receipt does not contain the "status" field. '
"Does your chain have Byzantium rules enabled?"
)
if receipt["status"] == 0:
raise ValueError("Status 0 indicates failure")
if txinfo["gas"] == receipt["gasUsed"]:
raise ValueError(f'Gas is completely used ({txinfo["gas"]}). Failure?')
return receipt, txinfo
示例13: main
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [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}")
示例14: channel_deposit
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def channel_deposit(token_network: Contract, assign_tokens: Callable) -> Callable:
def get(
channel_identifier: int,
participant: HexAddress,
deposit: int,
partner: HexAddress,
tx_from: Optional[HexAddress] = None,
) -> HexBytes:
tx_from = tx_from or participant
assign_tokens(tx_from, deposit)
txn_hash = call_and_transact(
token_network.functions.setTotalDeposit(
channel_identifier=channel_identifier,
participant=participant,
total_deposit=deposit,
partner=partner,
),
{"from": tx_from},
)
return txn_hash
return get
示例15: __hash_event
# 需要导入模块: import hexbytes [as 别名]
# 或者: from hexbytes import HexBytes [as 别名]
def __hash_event(self, event):
"""Returns the sha256 hash of an event dict.
Args:
event (dict): Event dict to hash.
Returns:
str: Hexadecimal hash string.
"""
# HACK: Be able to JSON serialize the AttributeDict/HexBytes objects https://github.com/ethereum/web3.py/issues/782
class CustomJsonEncoder(json.JSONEncoder):
def default(self, obj): # pylint: disable=E0202
if isinstance(obj, AttributeDict):
return obj.__dict__
if isinstance(obj, HexBytes):
return obj.hex()
return super().default(obj)
stringified_event = json.dumps(dict(event), sort_keys=True, cls=CustomJsonEncoder)
return sha256(stringified_event.encode()).hexdigest()