def test_auto_gas_computation_when_transacting(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.constructor("Caqalai").transact() deploy_receipt = web3.eth.waitForTransactionReceipt(deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) gas_estimate = string_contract.functions.setValue(to_bytes(text="ÄLÄMÖLÖ")).estimateGas() # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = transact(contract=string_contract, contract_function="setValue", func_args=[to_bytes(text="ÄLÄMÖLÖ")]) txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == gas_estimate + 100000
def test_transacting_with_contract_respects_explicit_gas(web3, STRING_CONTRACT, skip_if_testrpc, wait_for_block, call, transact): skip_if_testrpc(web3) wait_for_block(web3) StringContract = web3.eth.contract(**STRING_CONTRACT) deploy_txn = StringContract.constructor("Caqalai").transact() deploy_receipt = web3.eth.waitForTransactionReceipt(deploy_txn, 30) assert deploy_receipt is not None string_contract = StringContract(address=deploy_receipt['contractAddress']) # eth_abi will pass as raw bytes, no encoding # unless we encode ourselves txn_hash = transact(contract=string_contract, contract_function='setValue', func_args=[to_bytes(text="ÄLÄMÖLÖ")], tx_kwargs={'gas': 200000}) txn_receipt = web3.eth.waitForTransactionReceipt(txn_hash, 30) assert txn_receipt is not None final_value = call(contract=string_contract, contract_function='getValue') assert to_bytes(text=final_value) == to_bytes(text="ÄLÄMÖLÖ") txn = web3.eth.getTransaction(txn_hash) assert txn['gas'] == 200000
def generate_cache_key(value): """ Generates a cache key for the *args and **kwargs """ if is_bytes(value): return hashlib.md5(value).hexdigest() elif is_text(value): return generate_cache_key(to_bytes(text=value)) elif is_boolean(value) or is_null(value) or is_number(value): return generate_cache_key(repr(value)) elif is_dict(value): return generate_cache_key(( (key, value[key]) for key in sorted(value.keys()) )) elif is_list_like(value) or isinstance(value, Generator): return generate_cache_key("".join(( generate_cache_key(item) for item in value ))) else: raise TypeError("Cannot generate cache key for value {0} of type {1}".format( value, type(value), ))
def is_encodable(_type, value): if not isinstance(_type, str): raise ValueError("is_encodable only accepts type strings") base, sub, arrlist = process_type(_type) if arrlist: if not is_list_like(value): return False if arrlist[-1] and len(value) != arrlist[-1][0]: return False sub_type = (base, sub, arrlist[:-1]) return all(is_encodable(collapse_type(*sub_type), sub_value) for sub_value in value) elif base == 'address' and is_ens_name(value): # ENS names can be used anywhere an address is needed # Web3.py will resolve the name to an address before encoding it return True elif base == 'bytes' and isinstance(value, str): # Hex-encoded bytes values can be used anywhere a bytes value is needed if is_hex(value) and len(value) % 2 == 0: # Require hex-encoding of full bytes (even length) bytes_val = to_bytes(hexstr=value) return eth_abi_is_encodable(_type, bytes_val) else: return False elif base == 'string' and isinstance(value, bytes): # bytes that were encoded with utf-8 can be used anywhere a string is needed try: string_val = to_text(value) except UnicodeDecodeError: return False else: return eth_abi_is_encodable(_type, string_val) else: return eth_abi_is_encodable(_type, value)
def encode_rpc_request(self, method, params): return to_bytes(text=json.dumps({ "jsonrpc": "2.0", "method": method, "params": params or [], "id": next(self.request_counter), }))
def encode_rpc_request(self, method, params): rpc_dict = { "jsonrpc": "2.0", "method": method, "params": params or [], "id": next(self.request_counter), } encoded = FriendlyJsonSerde().json_encode(rpc_dict) return to_bytes(text=encoded)
to_bytes, ) from ethpm import ( ASSETS_DIR, Package, ) from ethpm.contract import ( LinkableContract, ) from web3 import Web3 from web3.pm import ( SimpleRegistry, ) from web3.tools.pytest_ethereum.deployer import ( Deployer, ) SOL_PACKAGE_ID_1 = to_bytes( hexstr='0x60c5112b61159e6b42d54d945078394e9d5fc9c6ff0f3df78977006f8bbc06d4' ) # noqa: E501 SOL_PACKAGE_ID_2 = to_bytes( hexstr='0xdbcfb0bd7115bf659350d77bb22bb889ca8294f61b0ca480f8a47bb8fc904cc9' ) # noqa: E501 SOL_PACKAGE_ID_3 = to_bytes( hexstr='0xf3e4002c48a7f8f3485d62988317849c175340b66517c3b2993f725643eba84b' ) # noqa: E501 SOL_RELEASE_ID_1 = to_bytes( hexstr='0x13414014c4f3c0ee41f1ede8e612e0377ae741f3abaa8d22e84e6b3759334fe9' ) # noqa: E501 SOL_RELEASE_ID_2 = to_bytes( hexstr='0x30cb63a88e721b461e294fa212af64f12e9500b3892e0e65fa70090ab63afb4d' ) # noqa: E501 SOL_RELEASE_ID_3 = to_bytes( hexstr='0x73f5fafa3d9bd5080d9b27c092cd65fdbf7c8f982df4d5d0de22eb2cd56f4fcb'
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())
('gas_limit', big_endian_int), ('gas_used', big_endian_int), ('timestamp', big_endian_int), ('extra_data', binary), #('mix_hash', binary), we have removed these 2 fields because we want a mining block header only #('nonce', Binary(8, allow_empty=True) ] provider = Web3.IPCProvider('/home/ubuntu/.ethereum/geth.ipc') w3 = Web3(provider) print(w3.isConnected()) blockNumber = int(sys.argv[1], 10) myHeader = MiningBlockHeader( parent_hash = to_bytes(int(w3.eth.getBlock(blockNumber).parentHash.hex(), 16)), uncles_hash = to_bytes(int(w3.eth.getBlock(blockNumber).sha3Uncles.hex(), 16)), coinbase = to_bytes(int(w3.eth.getBlock(blockNumber).miner, 16)), state_root = to_bytes(int(w3.eth.getBlock(blockNumber).stateRoot.hex(), 16)), transaction_root = to_bytes(int(w3.eth.getBlock(blockNumber).transactionsRoot.hex(), 16)), receipt_root = to_bytes(int(w3.eth.getBlock(blockNumber).receiptsRoot.hex(), 16)), bloom = int(w3.eth.getBlock(blockNumber).logsBloom.hex(), 16), difficulty = w3.eth.getBlock(blockNumber).difficulty, block_number = w3.eth.getBlock(blockNumber).number, gas_limit = w3.eth.getBlock(blockNumber).gasLimit, gas_used = w3.eth.getBlock(blockNumber).gasUsed, timestamp = w3.eth.getBlock(blockNumber).timestamp, extra_data = to_bytes(int(w3.eth.getBlock(blockNumber).extraData.hex(), 16)), #mix_hash = to_bytes(int(w3.eth.getBlock(blockNumber).mixHash.hex(), 16)), #nonce = to_bytes(int(w3.eth.getBlock(blockNumber).nonce.hex(), 16)), )
def _type_byte(self) -> bytes: return to_bytes(self._type_id)
def hex_to_bytes(data: str) -> bytes: return to_bytes(hexstr=HexStr(data))
) from web3.exceptions import ( InvalidAddress, ) from web3.middleware import ( construct_result_generator_middleware, construct_sign_and_send_raw_middleware, ) from web3.middleware.signing import ( gen_normalized_accounts, ) from web3.providers import ( BaseProvider, ) from web3.providers.eth_tester import ( EthereumTesterProvider, ) PRIVATE_KEY_1 = to_bytes( hexstr='0x6a8b4de52b288e111c14e1c4b868bc125d325d40331d86d875a3467dd44bf829' ) ADDRESS_1 = '0x634743b15C948820069a43f6B361D03EfbBBE5a8' PRIVATE_KEY_2 = to_bytes( hexstr='0xbf963e13b164c2100795f53e5590010f76b7a91b5a78de8e2b97239c8cfca8e8' ) ADDRESS_2 = '0x91eD14b5956DBcc1310E65DC4d7E82f02B95BA46' KEY_FUNCS = ( eth_keys.keys.PrivateKey, eth_account.Account.privateKeyToAccount, HexBytes, to_hex,
web3.eth.defaultAccount = accounts[0] plasma_contract = contract.Contract(web3) contr = plasma_contract.deploy_contract() block_init = web3.eth.getBlock("latest") deposit_filter = contr.events.Deposit.createFilter(fromBlock='latest') finalization_filter = contr.events.Finalization.createFilter( fromBlock='latest') start_exit_filter = contr.events.ExitStart.createFilter(fromBlock='latest') exits_finalized_filter = contr.events.ExitsFinalized.createFilter( fromBlock='latest') with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) print("Requesting Enclave initialization") s.sendall( to_bytes(text=create_enclave_initialization( block_init, plasma_contract.get_abi(), plasma_contract.get_address()))) data = s.recv(1024) json_data = json.loads(data) enclave_key = json_data[0] index = json_data[1] print('Received the Enclave Public Key: ', json.loads(data)) contr.functions.set_enclave(enclave_key).transact() print("Requesting Deposit of 10 for", accounts[0]) transactions, chain = deposit_on_contract(contr, deposit_filter) s.sendall(to_bytes(text=create_deposit_request(chain, transactions))) data = s.recv(1024) print( "Requesting Transaction from 0x49079aF95b9F45BdAcEc269f49BdC5F6185C2B44 " "to 0xdaa4599e4f584816ce665f7d3a89f020d12541a6")
ens.setup_address(name, TEST_ADDRESS) assert is_same_address(ens.address(name), TEST_ADDRESS) assert is_same_address(ens.address(equivalent), TEST_ADDRESS) ens.setup_address(name, None) assert ens.address(name) is None @pytest.mark.parametrize( 'set_address', [ # since the test uses getTransactionCount, # using a same address converted to bytes and hex will error with same count, # use two different addresses of each type (hex, bytes) "0x000000000000000000000000000000000000dEaD", to_bytes(hexstr="0x5B2063246F2191f18F2675ceDB8b28102e957458"), EMPTY_ADDR_HEX, None, '', ], ) def test_set_address_noop(ens, set_address): eth = ens.web3.eth owner = ens.owner('tester.eth') ens.setup_address('noop.tester.eth', set_address) starting_transactions = eth.getTransactionCount(owner) # do not issue transaction if address is already set ens.setup_address('noop.tester.eth', set_address) assert eth.getTransactionCount(owner) == starting_transactions
def ecdsa_decryption(message, provider_key_file, provider_password): (public_key_hex, private_key_hex) = get_keys_from_file(provider_key_file, provider_password) result = decryption(private_key_hex, to_bytes(hexstr=message)) return result.decode()
) from ethpm.contract import ( LinkableContract, ) from pytest_ethereum import ( linker, ) from pytest_ethereum.deployer import ( Deployer, ) from newchain_web3 import Web3 from newchain_web3.pm import ( SolidityReferenceRegistry, VyperReferenceRegistry, ) VY_PACKAGE_ID_1 = to_bytes( hexstr='0xd059e8a6ea5a8bbf8dd097a7b8922316dcb7f024e8220b56d3c9e7188a6a7640' ) # noqa: E501 VY_PACKAGE_ID_2 = to_bytes( hexstr='0x6df709a85698ad921462b8979547e3a873e22e1c73b1cb691f9376847fb2d402' ) # noqa: E501 VY_PACKAGE_ID_3 = to_bytes( hexstr='0x80e41a42e3b8c3af0ea51c3fd50d481eef1367dd9d3797ba93d35dcf60660882' ) # noqa: E501 VY_RELEASE_ID_1 = to_bytes( hexstr='0x595e26f1b2247bacc57e32807f8059e0b0837dd9c47e6946994196bd29c9ca97' ) # noqa: E501 VY_RELEASE_ID_2 = to_bytes( hexstr='0x04592cb9ced5413e1b09e87b089bf696a05efb76ee87c8c41259635fac6d938a' ) # noqa: E501 VY_RELEASE_ID_3 = to_bytes( hexstr='0xa06dbc51f8891894778ce03dc23d706d228c99789595758bd3dcac3a93f47f0a'
def value_encoder(value: int) -> bytes: return to_bytes(value)
) from web3.middleware import ( construct_result_generator_middleware, construct_sign_and_send_raw_middleware, ) from web3.middleware.signing import ( gen_normalized_accounts, ) from web3.providers import ( BaseProvider, ) from web3.providers.eth_tester import ( EthereumTesterProvider, ) PRIVATE_KEY_1 = to_bytes( hexstr='0x6a8b4de52b288e111c14e1c4b868bc125d325d40331d86d875a3467dd44bf829') ADDRESS_1 = '0x634743b15C948820069a43f6B361D03EfbBBE5a8' PRIVATE_KEY_2 = to_bytes( hexstr='0xbf963e13b164c2100795f53e5590010f76b7a91b5a78de8e2b97239c8cfca8e8') ADDRESS_2 = '0x91eD14b5956DBcc1310E65DC4d7E82f02B95BA46' KEY_FUNCS = ( eth_keys.keys.PrivateKey, eth_account.Account.privateKeyToAccount, HexBytes, to_hex, identity, )
from web3._utils.module_testing.emitter_contract import ( CONTRACT_EMITTER_ABI, CONTRACT_EMITTER_CODE, ) from web3._utils.module_testing.math_contract import ( MATH_ABI, MATH_BYTECODE, ) from web3._utils.module_testing.revert_contract import ( _REVERT_CONTRACT_ABI, REVERT_CONTRACT_BYTECODE, ) @pytest.fixture(scope="module", params=[lambda x: to_bytes(hexstr=x), identity]) def address_conversion_func(request): return request.param @pytest.fixture(scope="module") def math_contract_factory(web3): contract_factory = web3.eth.contract(abi=MATH_ABI, bytecode=MATH_BYTECODE) return contract_factory @pytest.fixture(scope="module") def emitter_contract_factory(web3): contract_factory = web3.eth.contract(abi=CONTRACT_EMITTER_ABI, bytecode=CONTRACT_EMITTER_CODE) return contract_factory
def toBytes(primitive: Primitives = None, hexstr: HexStr = None, text: str = None) -> bytes: return to_bytes(primitive, hexstr, text)
def _convert_hash(key): return "0x{}".format(encode_hex(sha3(to_bytes(hexstr=key))))
def get_ipfs_hash(hex_string): hex_string = remove_0x_prefix(hex_string) pad_hex_string = hex_string.rjust(64, "0") return b58encode(to_bytes(hexstr="1220" + pad_hex_string))
def transfer_async( self, registry_address: PaymentNetworkID, token_address: TokenAddress, amount: TokenAmount, target: Address, identifier: PaymentID = None, secret: Secret = None, secrethash: SecretHash = None, ): if not isinstance(amount, int): raise InvalidAmount("Amount not a number") if amount <= 0: raise InvalidAmount("Amount negative") if not is_binary_address(token_address): raise InvalidAddress("token address is not valid.") if not is_binary_address(target): raise InvalidAddress("target address is not valid.") if secret is not None: if len(secret) != SECRET_HEXSTRING_LENGTH: raise InvalidSecretOrSecretHash( "secret length should be " + str(SECRET_HEXSTRING_LENGTH) + "." ) if not is_hex(secret): raise InvalidSecretOrSecretHash("provided secret is not an hexadecimal string.") secret = to_bytes(hexstr=secret) if secrethash is not None: if len(secrethash) != SECRETHASH_HEXSTRING_LENGTH: raise InvalidSecretOrSecretHash( "secret_hash length should be " + str(SECRETHASH_HEXSTRING_LENGTH) + "." ) if not is_hex(secrethash): raise InvalidSecretOrSecretHash("secret_hash is not an hexadecimal string.") secrethash = to_bytes(hexstr=secrethash) # if both secret and secrethash were provided we check that sha3(secret) # matches the secerthash. Note that it is valid to provide a secert_hash # without providing a secret if secret is not None and secrethash is not None and secrethash != sha3(secret): raise InvalidSecretOrSecretHash("provided secret and secret_hash do not match.") valid_tokens = views.get_token_identifiers( views.state_from_raiden(self.raiden), registry_address ) if token_address not in valid_tokens: raise UnknownTokenAddress("Token address is not known.") log.debug( "Initiating transfer", initiator=pex(self.raiden.address), target=pex(target), token=pex(token_address), amount=amount, identifier=identifier, ) payment_network_identifier = self.raiden.default_registry.address token_network_identifier = views.get_token_network_identifier_by_token_address( chain_state=views.state_from_raiden(self.raiden), payment_network_id=payment_network_identifier, token_address=token_address, ) payment_status = self.raiden.mediated_transfer_async( token_network_identifier=token_network_identifier, amount=amount, target=target, identifier=identifier, secret=secret, secrethash=secrethash, ) return payment_status
def normalize_32_byte_hex_address(value): as_bytes = eth_utils.to_bytes(hexstr=value) return eth_utils.to_normalized_address(as_bytes[-20:])
def to_bytes32(primitive=None, hexstr=None, text=None): return to_bytes(primitive, hexstr, text).ljust(32, b"\x00")
def is_prefixed(value, prefix): return value.startswith( to_bytes(prefix) if is_bytes(value) else to_text(text=prefix) )
('nonce', Binary(8, allow_empty=True))] @property def hash(self) -> Hash32: return keccak(rlp.encode(self)) @property def mining_hash(self) -> Hash32: return keccak(rlp.encode(self[:-2], MiningHeader)) from eth_utils import to_bytes, to_hex header = BlockHeader(parent_hash=block['parentHash'], uncles_hash=block['sha3Uncles'], coinbase=to_bytes(int(block['miner'], 16)), state_root=block['stateRoot'], transaction_root=block['transactionsRoot'], receipt_root=block['receiptsRoot'], bloom=big_endian_to_int(block['logsBloom']), difficulty=block['difficulty'], block_number=block['number'], gas_limit=block['gasLimit'], gas_used=block['gasUsed'], timestamp=block['timestamp'], extra_data=block['extraData'], mix_hash=block['mixHash'], nonce=block['nonce']) from hexdump import hexdump hexdump(block['parentHash'])
def mk_contract_address(sender, nonce): sender_bytes = to_bytes(hexstr=sender) raw = rlp.encode([sender_bytes, nonce]) h = keccak(raw) address_bytes = h[12:] return to_checksum_address(address_bytes)
def process_vyper_args(*args: List[str]) -> Iterable[bytes]: for arg in args: yield to_bytes(text=arg)
def test_account(monkeypatch, create_account): monkeypatch.setattr(Account, "generate_private_key", lambda: to_bytes(WALLET_PRIVATE_KEY)) return create_account()
def sign_message_hash(key, msg_hash): signature = key.sign_msg_hash(msg_hash) (v_raw, r, s) = signature.vrs v = to_eth_v(v_raw) eth_signature_bytes = to_bytes32(r) + to_bytes32(s) + to_bytes(v) return (v, r, s, eth_signature_bytes)
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()
def to_standard_signature_bytes(ethereum_signature_bytes): rs = ethereum_signature_bytes[:-1] v = to_int(ethereum_signature_bytes[-1]) standard_v = to_standard_v(v) return rs + to_bytes(standard_v)
def uint256_to_bytes(uint): return to_bytes(uint).rjust(32, b'\0')
def deserialize_bytes(data: str) -> bytes: return to_bytes(hexstr=data)
def hex_to_bytes(s): return to_bytes(hexstr=s)
from eth.chains.mainnet import MAINNET_VM_CONFIGURATION from eth.chains.ropsten import ROPSTEN_VM_CONFIGURATION from p2p.exceptions import MalformedMessage from trinity.exceptions import ENRMissingForkID, RemoteChainIsStale, LocalChainIncompatibleOrStale from trinity.protocol.eth.forkid import ( extract_fork_blocks, extract_forkid, ForkID, make_forkid, validate_forkid, ) MAINNET_GENESIS_HASH = to_bytes( hexstr='0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' ) ROPSTEN_GENESIS_HASH = to_bytes( hexstr='0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d' ) def test_extract_fork_blocks(): fork_blocks = extract_fork_blocks(MAINNET_VM_CONFIGURATION) assert fork_blocks == (1150000, 1920000, 2463000, 2675000, 4370000, 7280000, 9069000, 9200000) @pytest.mark.parametrize( 'head,expected_forkid', [
try: import factory except ImportError: raise ImportError( "The p2p.tools.factories module requires the `factory_boy` library.") from eth_utils import to_bytes from eth.chains.mainnet import MAINNET_VM_CONFIGURATION from trinity.protocol.common.context import ChainContext from .db import AsyncHeaderDBFactory MAINNET_GENESIS_HASH = to_bytes( hexstr='0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' ) # noqa: E501 class ChainContextFactory(factory.Factory): class Meta: model = ChainContext network_id = 1 client_version_string = 'test' headerdb = factory.SubFactory(AsyncHeaderDBFactory) vm_configuration = ((0, MAINNET_VM_CONFIGURATION[-1][1]), ) listen_port = 30303 p2p_version = 5
import pytest from unittest.mock import ( Mock, ) from eth_utils import ( to_bytes, ) ABI = [{}] ADDRESS = '0xd3CdA913deB6f67967B99D67aCDFa1712C293601' BYTES_ADDRESS = to_bytes(hexstr=ADDRESS) NON_CHECKSUM_ADDRESS = '0xd3cda913deb6f67967b99d67acdfa1712c293601' INVALID_CHECKSUM_ADDRESS = '0xd3CDA913deB6f67967B99D67aCDFa1712C293601' @pytest.mark.parametrize( 'args,kwargs,expected', ( ((ADDRESS,), {}, None), ((BYTES_ADDRESS,), {}, None), ((INVALID_CHECKSUM_ADDRESS,), {}, ValueError), ((NON_CHECKSUM_ADDRESS,), {}, ValueError), ((), {'address': ADDRESS}, None), ((), {'address': INVALID_CHECKSUM_ADDRESS}, ValueError), ((), {'address': NON_CHECKSUM_ADDRESS}, ValueError), ) ) def test_contract_address_validation(web3, args, kwargs, expected): if isinstance(expected, type) and issubclass(expected, Exception): with pytest.raises(expected):
import pytest from eth_utils import ( to_bytes, ) from web3._utils.toolz import ( identity, ) from .utils import ( get_open_port, ) @pytest.fixture(scope="module", params=[lambda x: to_bytes(hexstr=x), identity]) def address_conversion_func(request): return request.param @pytest.fixture() def open_port(): return get_open_port()