Python hexbytes.HexBytes() Examples
The following are 30
code examples of hexbytes.HexBytes().
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
hexbytes
, or try the search function
.
Example #1
Source File: game.py From agents-aea with Apache License 2.0 | 7 votes |
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
Example #2
Source File: datatypes.py From brownie with MIT License | 6 votes |
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)
Example #3
Source File: decoder.py From django-eth-events with MIT License | 6 votes |
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
Example #4
Source File: root_event_listener.py From plasma-mvp with MIT License | 6 votes |
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()
Example #5
Source File: conftest.py From clove with GNU General Public License v3.0 | 6 votes |
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
Example #6
Source File: transaction.py From raiden-contracts with MIT License | 6 votes |
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
Example #7
Source File: test_reorg_detector.py From django-eth-events with MIT License | 6 votes |
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)
Example #8
Source File: mint_tokens.py From raiden-contracts with MIT License | 6 votes |
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: jsonexporter.py From ethgasstation-backend with GNU General Public License v3.0 | 6 votes |
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)
Example #10
Source File: test_reorg_detector.py From django-eth-events with MIT License | 6 votes |
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)
Example #11
Source File: test_utils.py From django-eth-events with MIT License | 6 votes |
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')))
Example #12
Source File: test_reorg_detector.py From django-eth-events with MIT License | 6 votes |
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)
Example #13
Source File: test_utils.py From django-eth-events with MIT License | 6 votes |
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'])
Example #14
Source File: channel.py From raiden-contracts with MIT License | 6 votes |
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
Example #15
Source File: account.py From brownie with MIT License | 6 votes |
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
Example #16
Source File: utils.py From raiden-contracts with MIT License | 5 votes |
def txn_gas(web3: Web3) -> Callable: def get(txn_hash: HexBytes) -> int: receipt = web3.eth.getTransactionReceipt(txn_hash) return receipt["gasUsed"] return get
Example #17
Source File: test_transaction.py From raiden-contracts with MIT License | 5 votes |
def test_check_successful_tx_with_nonexistent_status() -> None: """ check_successful_tx() with a receipt without status field should raise a KeyError """ web3_mock = Mock() web3_mock.eth.getTransactionReceipt.return_value = {"blockNumber": 300} txid = HexBytes("abcdef") with pytest.raises(KeyError): check_successful_tx(web3=web3_mock, txid=txid) web3_mock.eth.getTransactionReceipt.assert_called_with(txid) web3_mock.eth.getTransaction.assert_called_with(txid)
Example #18
Source File: utils.py From raiden-contracts with MIT License | 5 votes |
def get_block(web3: Web3) -> Callable: def get(txn_hash: HexBytes) -> int: receipt = web3.eth.getTransactionReceipt(txn_hash) return receipt["blockNumber"] return get
Example #19
Source File: channel.py From raiden-contracts with MIT License | 5 votes |
def withdraw_channel(token_network: Contract, create_withdraw_signatures: Callable) -> Callable: def get( channel_identifier: int, participant: HexAddress, withdraw_amount: int, expiration_block: int, partner: HexAddress, delegate: Optional[HexAddress] = None, ) -> HexBytes: delegate = delegate or participant channel_identifier = token_network.functions.getChannelIdentifier( participant, partner ).call() (signature_participant, signature_partner) = create_withdraw_signatures( [participant, partner], channel_identifier, participant, withdraw_amount, expiration_block, ) txn_hash = call_and_transact( token_network.functions.setTotalWithdraw( channel_identifier, participant, withdraw_amount, expiration_block, signature_participant, signature_partner, ), {"from": delegate}, ) return txn_hash return get
Example #20
Source File: test_transaction.py From raiden-contracts with MIT License | 5 votes |
def test_check_successful_tx_with_status_zero() -> None: web3_mock = Mock() web3_mock.eth.getTransactionReceipt.return_value = {"blockNumber": 300, "status": 0} txid = HexBytes("abcdef") with pytest.raises(ValueError): check_successful_tx(web3=web3_mock, txid=txid) web3_mock.eth.getTransactionReceipt.assert_called_with(txid) web3_mock.eth.getTransaction.assert_called_with(txid)
Example #21
Source File: test_decoder.py From django-ethereum-events with MIT License | 5 votes |
def setUpTestData(cls): super(DecoderTestCase, cls).setUpTestData() cls.eth_tester = EthereumTester(backend=PyEVMBackend()) cls.provider = EthereumTesterProvider(cls.eth_tester) cls.web3 = Web3(cls.provider) # Deploy the Bank test contract cls.bank_abi = json.loads(BANK_ABI_RAW) bank_bytecode = BANK_BYTECODE Bank = cls.web3.eth.contract(abi=cls.bank_abi, bytecode=bank_bytecode) tx_hash = Bank.constructor().transact() tx_receipt = cls.web3.eth.waitForTransactionReceipt(tx_hash) cls.bank_address = tx_receipt.contractAddress cls.bank_contract = cls.web3.eth.contract(address=cls.bank_address, abi=cls.bank_abi) # Take a snapshot of this state so far cls.clean_state_snapshot = cls.eth_tester.take_snapshot() # Log contains a LogDeposit event with the following arguments # owner: self.web3.eth.accounts[0] # amount: 1 ether with open(cls.events_log_file) as log_file: test_logs = json.load(log_file) # From web3 v3 to web3 v4, the topics as we as the blockHash, transactionHash are # wrapped with the HexBytes class. cls.logs = cls._proccess_logs(test_logs)
Example #22
Source File: __init__.py From shadowlands with MIT License | 5 votes |
def signed_tx(cls, sutx, v, r, s): enctx = encode_transaction(sutx, (v, r, s)) transaction_hash = keccak(enctx) attr_dict = AttributeDict({ 'rawTransaction': HexBytes(enctx), 'hash': HexBytes(transaction_hash), 'r': r, 's': s, 'v': v, }) return attr_dict
Example #23
Source File: exceptions.py From py-trie with MIT License | 5 votes |
def __init__(self, missing_node_hash: Hash32, nibbles_traversed: NibblesInput, *args) -> None: if not isinstance(missing_node_hash, bytes): raise TypeError("Missing node hash must be bytes, was: %r" % missing_node_hash) super().__init__(HexBytes(missing_node_hash), Nibbles(nibbles_traversed), *args)
Example #24
Source File: exceptions.py From py-trie with MIT License | 5 votes |
def requested_key(self) -> HexBytes: return self.args[2]
Example #25
Source File: exceptions.py From py-trie with MIT License | 5 votes |
def root_hash(self) -> HexBytes: return self.args[1]
Example #26
Source File: exceptions.py From py-trie with MIT License | 5 votes |
def missing_node_hash(self) -> HexBytes: return self.args[0]
Example #27
Source File: exceptions.py From py-trie with MIT License | 5 votes |
def __init__( self, missing_node_hash: Hash32, root_hash: Hash32, requested_key: bytes, prefix: Nibbles = None, *args): if not isinstance(missing_node_hash, bytes): raise TypeError("Missing node hash must be bytes, was: %r" % missing_node_hash) elif not isinstance(root_hash, bytes): raise TypeError("Root hash must be bytes, was: %r" % root_hash) elif not isinstance(requested_key, bytes): raise TypeError("Requested key must be bytes, was: %r" % requested_key) if prefix is not None: prefix_nibbles: Optional[Nibbles] = Nibbles(prefix) else: prefix_nibbles = None super().__init__( HexBytes(missing_node_hash), HexBytes(root_hash), HexBytes(requested_key), prefix_nibbles, *args, )
Example #28
Source File: context.py From evmlab with GNU General Public License v3.0 | 5 votes |
def findContractForBytecode(contracts, bytecode): if type(bytecode) is HexBytes: bytecode = Web3.toHex(bytecode) if bytecode.startswith('0x'): bytecode = bytecode[2:] for c in contracts: # ignore last 34 bytes which is just metadata if c.bin and c.bin[:-68] == bytecode[:-68] or c.binRuntime and c.binRuntime[:-68] == bytecode[:-68]: return c return None
Example #29
Source File: test_decoder.py From django-ethereum-events with MIT License | 5 votes |
def _proccess_logs(test_logs): logs = deepcopy(test_logs) for index, log in enumerate(test_logs): # Convert topics to HexBytes for z, topic in enumerate(log['topics']): logs[index]['topics'][z] = HexBytes(topic) # Convert blockHash and transactionHash to HexBytes logs[index]['transactionHash'] = HexBytes(log['transactionHash']) logs[index]['blockHash'] = HexBytes(log['blockHash']) return logs
Example #30
Source File: contract.py From tron-api-python with MIT License | 5 votes |
def decode_function_input(self, data): data = HexBytes(data) selector, params = data[:4], data[4:] func = self.get_function_by_selector(selector) names = [x['name'] for x in func.abi['inputs']] types = [x['type'] for x in func.abi['inputs']] decoded = decode_abi(types, params) normalized = map_abi_data(BASE_RETURN_NORMALIZERS, types, decoded) return func, dict(zip(names, normalized))