Python web3.Web3.toBytes() Examples
The following are 24
code examples of web3.Web3.toBytes().
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
web3.Web3
, or try the search function
.
Example #1
Source File: proofs.py From raiden-contracts with MIT License | 6 votes |
def pack_reward_proof( monitoring_service_contract_address: HexAddress, chain_id: ChainID, token_network_address: HexAddress, non_closing_participant: HexAddress, non_closing_signature: Signature, reward_amount: TokenAmount, ) -> bytes: return ( Web3.toBytes(hexstr=monitoring_service_contract_address) + encode_single("uint256", chain_id) + encode_single("uint256", MessageTypeId.MSReward) + Web3.toBytes(hexstr=token_network_address) + Web3.toBytes(hexstr=non_closing_participant) + non_closing_signature + encode_single("uint256", reward_amount) )
Example #2
Source File: proofs.py From raiden-contracts with MIT License | 6 votes |
def pack_withdraw_message( token_network_address: HexAddress, chain_identifier: ChainID, channel_identifier: ChannelID, participant: HexAddress, amount_to_withdraw: TokenAmount, expiration_block: BlockExpiration, ) -> bytes: return ( Web3.toBytes(hexstr=token_network_address) + encode_single("uint256", chain_identifier) + encode_single("uint256", MessageTypeId.WITHDRAW) + encode_single("uint256", channel_identifier) + Web3.toBytes(hexstr=participant) + encode_single("uint256", amount_to_withdraw) + encode_single("uint256", expiration_block) )
Example #3
Source File: proofs.py From raiden-contracts with MIT License | 6 votes |
def pack_cooperative_settle_message( token_network_address: HexAddress, chain_identifier: ChainID, channel_identifier: ChannelID, participant1_address: HexAddress, participant1_balance: TokenAmount, participant2_address: HexAddress, participant2_balance: TokenAmount, ) -> bytes: return ( Web3.toBytes(hexstr=token_network_address) + encode_single("uint256", chain_identifier) + encode_single("uint256", MessageTypeId.COOPERATIVE_SETTLE) + encode_single("uint256", channel_identifier) + Web3.toBytes(hexstr=participant1_address) + encode_single("uint256", participant1_balance) + Web3.toBytes(hexstr=participant2_address) + encode_single("uint256", participant2_balance) )
Example #4
Source File: test_setup_name.py From web3.py with MIT License | 6 votes |
def test_setup_name(ens, name, normalized_name, namehash_hex): address = ens.web3.eth.accounts[3] assert not ens.name(address) owner = ens.owner('tester.eth') ens.setup_name(name, address) assert ens.name(address) == normalized_name # check that the correct namehash is set: node = Web3.toBytes(hexstr=namehash_hex) assert ens.resolver(normalized_name).caller.addr(node) == address # check that the correct owner is set: assert ens.owner(name) == owner ens.setup_name(None, address) ens.setup_address(name, None) assert not ens.name(address) assert not ens.address(name)
Example #5
Source File: test_setup_address.py From web3.py with MIT License | 6 votes |
def test_set_address(ens, name, full_name, namehash_hex, TEST_ADDRESS): assert ens.address(name) is None owner = ens.owner('tester.eth') ens.setup_address(name, TEST_ADDRESS) assert is_same_address(ens.address(name), TEST_ADDRESS) namehash = Web3.toBytes(hexstr=namehash_hex) normal_name = ens.nameprep(full_name) assert is_same_address(ens.address(name), TEST_ADDRESS) # check that the correct namehash is set: assert is_same_address(ens.resolver(normal_name).caller.addr(namehash), TEST_ADDRESS) # check that the correct owner is set: assert ens.owner(name) == owner ens.setup_address(name, None) assert ens.address(name) is None
Example #6
Source File: proofs.py From raiden-contracts with MIT License | 6 votes |
def pack_balance_proof( token_network_address: HexAddress, chain_identifier: ChainID, channel_identifier: ChannelID, balance_hash: BalanceHash, nonce: Nonce, additional_hash: AdditionalHash, msg_type: MessageTypeId, ) -> bytes: return ( Web3.toBytes(hexstr=token_network_address) + encode_single("uint256", chain_identifier) + encode_single("uint256", msg_type) + encode_single("uint256", channel_identifier) + balance_hash + encode_single("uint256", nonce) + additional_hash )
Example #7
Source File: api.py From raiden-services with MIT License | 5 votes |
def is_signature_valid(self) -> bool: packed_data = self.sender + self.receiver + Web3.toBytes(text=self.timestamp_str) try: recovered_address = recover(packed_data, self.signature) except InvalidSignature: return False return is_same_address(recovered_address, self.sender)
Example #8
Source File: __init__.py From py-etherdelta with MIT License | 5 votes |
def solidity_sha256(self, abi_types, values): # TODO #normalized_values = map_abi_data([abi_ens_resolver(Web3)], abi_types, values) normalized_values = map_abi_data([], abi_types, values) #print(normalized_values) hex_string = add_0x_prefix(''.join( remove_0x_prefix(hex_encode_abi_type(abi_type, value)) for abi_type, value in zip(abi_types, normalized_values) )) hash_object = hashlib.sha256(Web3.toBytes(hexstr=hex_string)) return hash_object.hexdigest()
Example #9
Source File: __init__.py From py-etherdelta with MIT License | 5 votes |
def get_available_volume(self, token_addr, order_id): """ Returns available volume for an order give order ID :param token_addr: token address :type token_addr: str :param order_id: order ID :type order_id: str :return: available volume :rtype: int """ order = self.get_order(token_addr, order_id) if order == None: return None amountGet = int('{:.0f}'.format(Decimal(order['amountGet']))) amountGive = int('{:.0f}'.format(Decimal(order['amountGive']))) tokenGet = Web3.toChecksumAddress(order['tokenGet']) tokenGive = Web3.toChecksumAddress(order['tokenGive']) expires = int(order['expires']) nonce = int(order['nonce']) user = Web3.toChecksumAddress(order['user']) v = int(order['v']) r = Web3.toBytes(hexstr=order['r']) s = Web3.toBytes(hexstr=order['s']) available_volume = self.contractEtherDelta.call().availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) return available_volume
Example #10
Source File: __init__.py From py-etherdelta with MIT License | 5 votes |
def get_amount_filled(self, token_addr, order_id): """ Returns amount filled for an order given order ID :param token_addr: token address :type token_addr: str :param order_id: order ID :type order_id: str :return: filled amount :rtype: int """ order = self.get_order(token_addr, order_id) if order == None: return None amountGet = int('{:.0f}'.format(Decimal(order['amountGet']))) amountGive = int('{:.0f}'.format(Decimal(order['amountGive']))) tokenGet = Web3.toChecksumAddress(order['tokenGet']) tokenGive = Web3.toChecksumAddress(order['tokenGive']) expires = int(order['expires']) nonce = int(order['nonce']) user = Web3.toChecksumAddress(order['user']) v = int(order['v']) r = Web3.toBytes(hexstr=order['r']) s = Web3.toBytes(hexstr=order['s']) amount_filled = self.contractEtherDelta.call().amountFilled(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s) return amount_filled
Example #11
Source File: test_monitoring_service.py From raiden-contracts with MIT License | 5 votes |
def test_updateReward( monitoring_service_internals: Contract, ms_address: HexAddress, token_network: Contract, monitor_data_internal: Dict, ) -> None: A, B = monitor_data_internal["participants"] reward_identifier = Web3.keccak( encode_single("uint256", monitor_data_internal["channel_identifier"]) + Web3.toBytes(hexstr=token_network.address) ) def update_with_nonce(nonce: int) -> None: call_and_transact( monitoring_service_internals.functions.updateRewardPublic( token_network.address, A, B, REWARD_AMOUNT, nonce, ms_address, monitor_data_internal["non_closing_signature"], monitor_data_internal["reward_proof_signature"], ), {"from": ms_address}, ) # normal first call succeeds update_with_nonce(2) assert monitoring_service_internals.functions.rewardNonce(reward_identifier).call() == 2 # calling again with same nonce fails with pytest.raises(TransactionFailed, match="stale nonce"): update_with_nonce(2) # calling again with higher nonce succeeds update_with_nonce(3) assert monitoring_service_internals.functions.rewardNonce(reward_identifier).call() == 3
Example #12
Source File: proofs.py From raiden-contracts with MIT License | 5 votes |
def eth_sign_hash_message(encoded_message: bytes) -> bytes: signature_prefix = "\x19Ethereum Signed Message:\n" return Web3.keccak( Web3.toBytes(text=signature_prefix) + Web3.toBytes(text=str(len(encoded_message))) + encoded_message )
Example #13
Source File: test_conversions.py From web3.py with MIT License | 5 votes |
def test_to_bytes_hexstr(val, expected): assert Web3.toBytes(hexstr=val) == expected
Example #14
Source File: test_conversions.py From web3.py with MIT License | 5 votes |
def test_to_bytes_primitive(val, expected): assert Web3.toBytes(val) == expected
Example #15
Source File: conftest.py From web3.py with MIT License | 5 votes |
def bytes32(val): if isinstance(val, int): result = Web3.toBytes(val) else: raise TypeError('val %r could not be converted to bytes') if len(result) < 32: return result.rjust(32, b'\0') else: return result
Example #16
Source File: ethereum.py From agents-aea with Apache License 2.0 | 5 votes |
def __init__(self, private_key_path: Optional[str] = None): """ Instantiate an ethereum crypto object. :param private_key_path: the private key path of the agent """ super().__init__(private_key_path=private_key_path) bytes_representation = Web3.toBytes(hexstr=self.entity.key.hex()) self._public_key = str(keys.PrivateKey(bytes_representation).public_key) self._address = str(self.entity.address)
Example #17
Source File: utils.py From casper with The Unlicense | 5 votes |
def encode_int32(val): return Web3.toBytes(val).rjust(32, b'\x00')
Example #18
Source File: contract.py From clove with GNU General Public License v3.0 | 5 votes |
def redeem(self, secret: str) -> EthereumTokenTransaction: ''' Creates transaction that can redeem a contract. Args: secret (str): transaction secret that should match the contract secret hash (after hashing) Returns: EthereumTokenTransaction: unsigned transaction object with redeem transaction Raises: ValueError: if contract balance is 0 ''' if self.balance == 0: raise ValueError("Balance of this contract is 0.") contract = self.contract redeem_func = contract.functions.redeem(secret) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.recipient_address), 'value': 0, 'gas': ETH_REDEEM_GAS_LIMIT, } tx_dict = redeem_func.buildTransaction(tx_dict) transaction = EthereumTokenTransaction(network=self.network) transaction.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=tx_dict['gas'], to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), ) transaction.value = self.value transaction.token = self.token transaction.recipient_address = self.recipient_address return transaction
Example #19
Source File: contract.py From clove with GNU General Public License v3.0 | 5 votes |
def __init__(self, network, tx_dict): self.network = network self.tx_dict = tx_dict self.abi = self.network.abi self.method_id = self.network.extract_method_id(tx_dict['input']) self.type = self.network.get_method_name(self.method_id) self.token = None if self.method_id != self.network.initiate: logger.warning('Not a contract transaction.') raise ValueError('Not a contract transaction.') input_types = get_abi_input_types(find_matching_fn_abi(self.abi, fn_identifier=self.type)) input_names = get_abi_input_names(find_matching_fn_abi(self.abi, fn_identifier=self.type)) input_values = decode_abi(input_types, Web3.toBytes(hexstr=self.tx_dict['input'][10:])) self.inputs = dict(zip(input_names, input_values)) self.locktime = datetime.utcfromtimestamp(self.inputs['_expiration']) self.recipient_address = Web3.toChecksumAddress(self.inputs['_participant']) self.refund_address = self.tx_dict['from'] self.secret_hash = self.inputs['_hash'].hex() self.contract_address = Web3.toChecksumAddress(self.tx_dict['to']) self.block_number = self.tx_dict['blockNumber'] self.confirmations = self.network.get_latest_block - self.block_number self.balance = self.get_balance() if self.is_token_contract: self.value_base_units = self.inputs['_value'] self.token_address = Web3.toChecksumAddress(self.inputs['_token']) self.token = self.network.get_token_by_address(self.token_address) self.value = self.token.value_from_base_units(self.value_base_units) self.symbol = self.token.symbol else: self.value_base_units = self.tx_dict['value'] self.value = self.network.value_from_base_units(self.value_base_units) self.symbol = self.network.default_symbol
Example #20
Source File: base.py From clove with GNU General Public License v3.0 | 5 votes |
def extract_secret_from_redeem_transaction(self, tx_address: str) -> str: ''' Extracting secret from redeem transaction. Args: tx_address (str): address of the redeem transaction Returns: str,: Secret string Raises: ValueError: When given transaction was not a redeem type transaction Example: >>> from clove.network import EthereumTestnet >>> network = EthereumTestnet() >>> network.extract_secret_from_redeem_transaction('0x9e41847c3cc780e4cb59902cf55657f0ee92642d9dee4145e090cbf206d4748f') # noqa: E501 b2eefaadbbefeb9d9467092b612464db7c6724f71b5c1d70c85853845728f0e9 ''' tx_dict = self.get_transaction(tx_address) method_id = self.extract_method_id(tx_dict['input']) if method_id != self.redeem: logger.debug('Not a redeem transaction.') raise ValueError('Not a redeem transaction.') method_name = self.get_method_name(method_id) input_types = get_abi_input_types(find_matching_fn_abi(self.abi, fn_identifier=method_name)) input_values = decode_abi(input_types, Web3.toBytes(hexstr=tx_dict['input'][10:])) return input_values[0].hex()
Example #21
Source File: transaction.py From clove with GNU General Public License v3.0 | 5 votes |
def set_contract(self): self.contract = self.network.web3.eth.contract(address=self.contract_address, abi=self.abi) initiate_func = self.contract.functions.initiate( self.locktime_unix, self.secret_hash, self.recipient_address, self.token_address, bool(self.token), self.token_value_base_units, ) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.sender_address), 'from': self.sender_address, 'value': self.value_base_units, } tx_dict = initiate_func.buildTransaction(tx_dict) self.gas_limit = initiate_func.estimateGas({ key: value for key, value in tx_dict.items() if key not in ('to', 'data') }) self.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=self.gas_limit, to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), )
Example #22
Source File: transaction.py From clove with GNU General Public License v3.0 | 4 votes |
def __init__( self, network, sender_address: str, value: Decimal, token=None, ): super().__init__(network) self.sender_address = self.network.unify_address(sender_address) self.value = value self.token = token self.value_base_units = self.token.value_to_base_units(self.value) self.token_address = self.token.token_address self.symbol = self.token.symbol self.contract = self.network.web3.eth.contract(address=self.token_address, abi=self.token.approve_abi) approve_func = self.contract.functions.approve( self.network.contract_address, self.value_base_units, ) tx_dict = { 'nonce': self.network.web3.eth.getTransactionCount(self.sender_address), 'from': self.sender_address, } tx_dict = approve_func.buildTransaction(tx_dict) self.gas_limit = approve_func.estimateGas({ key: value for key, value in tx_dict.items() if key not in ('to', 'data') }) self.tx = Transaction( nonce=tx_dict['nonce'], gasprice=tx_dict['gasPrice'], startgas=self.gas_limit, to=tx_dict['to'], value=tx_dict['value'], data=Web3.toBytes(hexstr=tx_dict['data']), )
Example #23
Source File: __init__.py From py-etherdelta with MIT License | 4 votes |
def trade(self, order, eth_amount, user_private_key): """ Invokes on-chain trade :param order: order :type order: object :param eth_amount: ETH amount :type eth_amount: float :param user_private_key: user private key :type user_private_key: string :return: tx :rtype: object """ global web3, addressEtherDelta userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address # Transaction info maxGas = 250000 gasPriceWei = 1000000000 # 1 Gwei if order['tokenGive'] == '0x0000000000000000000000000000000000000000': ordertype = 'buy' # it's a buy order so we are selling tokens for ETH amount = eth_amount / float(order['price']) else: ordertype = 'sell' # it's a sell order so we are buying tokens for ETH amount = eth_amount amount_in_wei = web3.toWei(amount, 'ether') print("\nTrading " + str(eth_amount) + " ETH of tokens (" + str(amount) + " tokens) against this " + ordertype + " order: %.10f tokens @ %.10f ETH/token" % (float(order['ethAvailableVolume']), float(order['price']))) print("Details about order: " + str(order)) # trade function arguments kwargs = { 'tokenGet' : Web3.toChecksumAddress(order['tokenGet']), 'amountGet' : int(Decimal(order['amountGet'])), 'tokenGive' : Web3.toChecksumAddress(order['tokenGive']), 'amountGive' : int(Decimal(order['amountGive'])), 'expires' : int(order['expires']), 'nonce' : int(order['nonce']), 'user' : Web3.toChecksumAddress(order['user']), 'v' : order['v'], 'r' : w3.toBytes(hexstr=order['r']), 's' : w3.toBytes(hexstr=order['s']), 'amount' : int(amount_in_wei), } # Bail if there's no private key if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long') # Build binary representation of the function call with arguments abidata = self.contractEtherDelta.encodeABI('trade', kwargs=kwargs) print("abidata: " + str(abidata)) nonce = w3.eth.getTransactionCount(userAccount) # Override to have same as other transaction: #nonce = 53 print("nonce: " + str(nonce)) transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1} print(transaction) signed = w3.eth.account.signTransaction(transaction, user_private_key) print("signed: " + str(signed)) result = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction)) print("Transaction returned: " + str(result)) print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(result)) return result
Example #24
Source File: __init__.py From py-etherdelta with MIT License | 4 votes |
def cancel_order(self, order, user_private_key): """ Cancels an order on-chain :param order: order :type order: object :param user_private_key: user private key :type user_private_key: string :return: tx :rtype: object """ global w3, addressEtherDelta userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address # Transaction info maxGas = 250000 gasPriceWei = 1000000000 # 1 Gwei print("\nCancelling") print("Details about order: " + str(order)) # trade function arguments kwargs = { 'tokenGet' : Web3.toChecksumAddress(order['tokenGet']), 'amountGet' : int(Decimal(order['amountGet'])), 'tokenGive' : Web3.toChecksumAddress(order['tokenGive']), 'amountGive' : int(Decimal(order['amountGive'])), 'expires' : int(order['expires']), 'nonce' : int(order['nonce']), 'v' : order['v'], 'r' : w3.toBytes(hexstr=order['r']), 's' : w3.toBytes(hexstr=order['s']), } # Bail if there's no private key if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long') # Build binary representation of the function call with arguments abidata = self.contractEtherDelta.encodeABI('cancelOrder', kwargs=kwargs) print("abidata: " + str(abidata)) nonce = w3.eth.getTransactionCount(userAccount) # Override to have same as other transaction: #nonce = 53 print("nonce: " + str(nonce)) transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1} print(transaction) signed = w3.eth.account.signTransaction(transaction, user_private_key) print("signed: " + str(signed)) result = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction)) print("Transaction returned: " + str(result)) print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(result)) return result # This function is very similar to Web3.soliditySha3() but there is no Web3.solidity_sha256() as per November 2017 # It serializes values according to the ABI types defined in abi_types and hashes the result with sha256.